简体   繁体   English

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

[英]Generic Function without Input Parameter in Swift?

I have a generic Swift function like this: 我有一个通用的Swift函数,如下所示:

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? 如何在没有输入参数的情况下在Swift中调用Generic函数?

You need to tell Swift what the return type needs to be through some calling context: 你需要通过一些调用上下文告诉Swift返回类型是什么:

// 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. 注意,在后一种情况下,只有当someCall采用类似于Any的模糊类型作为其参数时,才需someCall 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() ) 相反, someCall被指定为[Int]作为参数,函数本身提供上下文,你可以只写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: +)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM