这是因为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
驾驶的是什么T
的决心是:
// 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
不false
,因为它是为NSObject
检查(因为c.dynamicType
结果的类型是NSObject.Type
不NSNumber.Type
)。
你是对的! –