那是因为t 确实不是类型。它是Metatype 类型的实例:
let x = NSString.self
// compiler error because the following is
// always true but you get the idea...
x is NSString.Type
您只想检查T,它是实际类型,但可以使用T.Type 来确定@987654326@ 是什么:
// genericised a bit, to make list an argument
func contains
<S: SequenceType, T>
(list: S, type t: T.Type) -> Bool {
for element in list {
if element is T {
return true
}
}
return false
}
let a = ["a","b","c"]
contains(a, type: String.self) // true
contains(a, type: NSString.self) // true
contains(a, type: Int.self) // false
contains(a, type: NSNumber.self) // false
let b: [Any] = [1, 2 as NSNumber, "c" as NSString]
contains(b, type: String.self) // true
contains(b, type: NSString.self) // true
contains(b, type: Int.self) // true
contains(b, type: NSNumber.self) // true
请记住,T 在编译时仍然是静态确定的,而不是动态确定的。所以:
let c: NSObject = 1 as NSNumber
contains(a, type: c.dynamicType)
返回true not false,因为它正在检查NSObject(因为c.dynamicType的结果类型是NSObject.Type而不是NSNumber.Type)。