有没有办法通过函数传递类类型并尝试将类转换为给定的类类型?我试过以下代码。
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'
您可以使用泛型函数并将类型参数限制为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
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
}
}
}