Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Function without Input Parameter in Swift?

Tags:

ios

swift

I have a generic Swift function like this:

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

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

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

but it did not work.

How do I call a Generic function in Swift without input parameters?

like image 342
confile Avatar asked Apr 17 '15 11:04

confile


1 Answers

You need to tell Swift what the return type needs to be through some calling context:

// either
let a: [Int] = jList.toNSArray()

// or, if you aren’t assigning to a variable
someCall( jList.toNSArray() as [Int] )

Note, in the latter case, this would only be necessary if someCall took a vague type like Any as its argument. If instead, someCall is specified to take an [Int] as an argument, the function itself provides the context and you can just write someCall( jList.toNSArray() )

In fact sometimes the context can be very tenuously inferred! 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: +)
like image 78
Airspeed Velocity Avatar answered Sep 21 '22 00:09

Airspeed Velocity