有没有办法通过函数传递类类型并尝试将类转换为给定的类类型?我尝试了以下代码。
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'
您可以使用泛型函数并将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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句