2014-12-30 47 views
5

考虑一个简单的例子通行证类型泛型函数和比较

func contains<T>(type t: T.Type) -> Bool { 
    for i in 0..<list.count { 
     if list[i] is t { // compiler says: 't' is not a type 
      return true 
     } 
    } 
    return false 
} 

编译器与

't' is not a type 

响应既然不能声明静态类型和做一次检查与is MyStaticType,我怎么能做到这在Swift中用泛型?

回答

3

你应该检查它是否是T

if list[i] is T { 
    ... 
} 
+0

你是对的! –

2

这是因为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) 

回报truefalse,因为它是为NSObject检查(因为c.dynamicType结果的类型是NSObject.TypeNSNumber.Type)。