为什么这个函数不能编译?提示是:二元运算符“===”不能应用于 I.Type 和 T.Type 类型的操作数。
func checkTypeOf<I, T>(instance: I, type: T.Type) {
print("\(instance) \(I.self === type ? "is" : "is not") a \(type)")
}
相比之下,这里有一个编译运行的例子:
class Dog {
@objc static var whatADogSays : String = "woof"
}
class NoisyDog : Dog {
}
func typeTester(d:Dog, _ whattype:Dog.Type) {
print("The \(d.dynamicType) \(d.dynamicType === whattype ? "is" : "is not") a \(whattype)")
}
typeTester(NoisyDog(), Dog.self)
最佳答案
您可能需要将参数限制为 AnyType
,因为 === 仅适用于 AnyObject。
func checkTypeOf<I: AnyObject, T: AnyObject>(instance: I, type: T.Type) {
print("\(instance) \(I.self === type ? "is" : "is not") a \(type)")
}
这里是===
操作符的定义
@warn_unused_result
public func ===(lhs: AnyObject?, rhs: AnyObject?) -> Bool
关于swift - 编译器不允许我比较类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36426673/