Swift中没有输入参数的通用函数?

时间:2015-04-17 11:05:37

标签: ios swift

我有一个像这样的通用Swift函数:

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

编译器没有错误,但我不知道如何调用此函数。我试过了:

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

但它不起作用。

如何在没有输入参数的情况下在Swift中调用Generic函数?

1 个答案:

答案 0 :(得分:13)

你需要告诉Swift返回类型需要通过一些调用上下文:

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

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

注意,在后一种情况下,只有在someCall采用类似Any的模糊类型作为其参数时才需要这样做。相反,如果指定someCall[Int]作为参数,则函数本身提供上下文,您只需编写someCall( jList.toNSArray() )

事实上,有时可以非常推断上下文!这有效,例如:

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: +)
相关问题