Swift 将类类型作为函数参数传递,并将其用作?下课

Swift 将类类型作为函数参数传递,并将其用作?下课,swift,type-inference,Swift,Type Inference,有没有办法通过函数传递一个类类型,并尝试将一个类转换为给定的类类型?我尝试了以下代码 class Section {} class TimeSection: Section {} class TaskSection: Section {} let timeSection = TimeSection() let taskSection = TaskSection() let sections = [timeSection, taskSection] func findSection(from

有没有办法通过函数传递一个类类型,并尝试将一个类转换为给定的类类型?我尝试了以下代码

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'

classType
实际上不是一个类型。它是一个保存
节的实例的参数。键入
。因此,您不能将其与
作为?
一起使用

由于它是一个参数,您可以将其与
=
进行比较。
==
的另一面应该是
节的元类型的实例,它可以通过
类型(of:)
获得

Swift 4.2 可以使用泛型函数并将类型参数限制为节

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
<代码>导入基础 类节{} 类TimeSection:节{} 类TaskSection:节{} 类NoSection{} 让timeSection=timeSection() 让taskSection=taskSection() let sections=[timeSection,taskSection] func findSection(来自类类型:T.Type){ 一节接一节{ guard let section=节为?T else{continue} 打印(“找到的节:\(节)”) } } findSection(from:TimeSection.self)//找到的节:\uuu lldb\u expr\u9.TimeSection findSection(from:TaskSection.self)//找到的节:\uuu lldb\u expr\u 9.TaskSection findSection(from:NoSection.self)//不会编译
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