General function without input parameter in Swift?

I have a general Swift function:

func toNSArray<T>() -> [T] { ... } 

The compiler gives no errors, but I do not know how to call this function. I tried:

 jList.toNSArray<String>() jList.<String>toNSArray() 

but it didn’t work.

How to call a Generic function in Swift without input parameters?

+6
source share
1 answer

You need to tell Swift what type of return should be through some call context:

 // either let a: [Int] = jList.toNSArray() // or, if you aren't assigning to a variable someCall( jList.toNSArray() as [Int] ) 

Note that in the latter case, this would be necessary only if someCall used an undefined type of type Any as an argument. If instead someCall specified to take [Int] as an argument, the function itself provides a context, and you can simply write someCall( jList.toNSArray() )

In fact, sometimes the context can be very subtly deduced! This works for example:

 extension Array { func asT<T>() -> [T] { var results: [T] = [] for x in self { if let y = x as? T { results.append(y) } } return results } } let a: [Any] = [1,2,3, "heffalump"] // here, it's the 0, defaulting to Int, that tells asT what T is... a.asT().reduce(0, combine: +) 
+12
source

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


All Articles