Pass Type to Common Function and Compare

Consider this simple example.

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 } 

The compiler is responsible

 't' is not a type 

Since I cannot declare a static type and do a check with is MyStaticType , how can I do this in Swift using generics?

+5
source share
2 answers

You should check if there is T :

 if list[i] is T { ... } 
+3
source

This is because t really not a type. This is an instance of type Metatype :

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

You just want to check t , which is the actual type, but you can use T.Type to determine if 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 

Remember that t is still defined statically at compile time, and not dynamically. So:

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

returns true not false because it checks for an NSObject (since the result type of c.dynamicType is NSObject.Type not NSNumber.Type ).

+2
source

Source: https://habr.com/ru/post/1210131/


All Articles