将 class 类型作为函数参数传递并用作?施放 class
Pass class type as a function parameter and use as? to cast the class
有没有办法通过函数传递 class 类型并尝试将 class 转换为给定的 class 类型?我尝试了以下代码。
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
实际上不是一个类型。它是一个包含 Section.Type
实例的参数。因此,您不能将它与 as?
.
一起使用
既然是参数,可以和==
比较一下。 ==
的另一边应该是section
的metatype的一个实例,可以通过type(of:)
获取。
func findSection(from classType: Section.Type) {
for section in sections {
if type(of: section) == classType {
print("Found section")
break
}
}
}
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
有没有办法通过函数传递 class 类型并尝试将 class 转换为给定的 class 类型?我尝试了以下代码。
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
实际上不是一个类型。它是一个包含 Section.Type
实例的参数。因此,您不能将它与 as?
.
既然是参数,可以和==
比较一下。 ==
的另一边应该是section
的metatype的一个实例,可以通过type(of:)
获取。
func findSection(from classType: Section.Type) {
for section in sections {
if type(of: section) == classType {
print("Found section")
break
}
}
}
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