将类类型作为函数参数传递并用作?投这堂课

问题描述 投票:1回答:2

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

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'
swift type-inference
2个回答
3
投票

Swift 4.2

您可以使用泛型函数并将类型参数限制为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

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
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.