2014-12-30 11 views
5

karşılaştırmak nasıl başarabilirsiniz bu basit bir örnekGeçiş jenerik işlevine tipi ve

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 
} 

ben statik türü bildirmek ve is MyStaticType bir çek yapamaz beri derleyici

't' is not a type 

ile yanıt düşünün Bu Swift ile jenerikler?

cevap

3

o T var olmadığını kontrol etmelidir:

t gerçekten bir tür olmadığı için değil
if list[i] is T { 
    ... 
} 
+0

Kesinlikle haklısınız! –

2

.

let x = NSString.self 
// compiler error because the following is 
// always true but you get the idea... 
x is NSString.Type 

Sadece gerçek türüdür T karşı denetlemek istediğiniz ama ne T belirlenmesini sürmek için T.Type kullanabileceği başka:

// 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 

Ayı O tip Metatype örneğidir var Bununla birlikte, T hala dinamik olarak değil, derleme zamanında statik olarak belirleniyor. Yani:

let c: NSObject = 1 as NSNumber 
contains(a, type: c.dynamicType) 

döner truedeğilfalse, (c.dynamicType sonucunun türü NSObject.Type değil NSNumber.Type olduğu için) o NSObject kontrol çünkü.