将类类型作为函数参数传递并用作?上课

时间:2018-12-05 08:01:31

标签: swift type-inference

是否可以通过函数传递类类型并尝试将类转换为给定的类类型?我尝试了以下代码。

class Section {}
class TimeSection: Section {}
class TaskSection: Section {}

let timeSection = TimeSection()
let taskSection = TaskSection()

let sections = [timeSection, taskSection]

func findSection(from classType: Section.Type) {
    for section in sections {
        guard let section = section as? classType else { continue }

        print("Found section")
    }
}

findSection(from: TimeSection.self)

但是我总是会收到此错误:

Use of undeclared type 'classType'

2 个答案:

答案 0 :(得分:3)

雨燕4.2

您可以使用泛型函数并将type参数限制为Section。

import Foundation

class Section {}
class TimeSection: Section {}
class TaskSection: Section {}
class NoSection {}

let timeSection = TimeSection()
let taskSection = TaskSection()

let sections = [timeSection, taskSection]

func findSection<T: Section>(from classType: T.Type) {
    for section in sections {
        guard let section = section as? T else { continue }

        print("Found section: \(section)")
    }
}

findSection(from: TimeSection.self) // Found section: __lldb_expr_9.TimeSection
findSection(from: TaskSection.self) // Found section: __lldb_expr_9.TaskSection
findSection(from: NoSection.self) // won't compile

答案 1 :(得分:0)

classType实际上不是一种类型。它是一个包含Section.Type实例的参数。因此,您不能将其与as?一起使用。

由于它是一个参数,因此可以将其与==进行比较。 ==的另一端应该是section的元类型的实例,可以由type(of:)获取。

func findSection(from classType: Section.Type) {
    for section in sections {
        if type(of: section) == classType {
            print("Found section")
            break
        }
    }
}