如何将数组传递给可变参数的函数?
static func apply<T>(fn: (T ...) -> T, xs: [T]) -> T {
return fn(xs) // gives '[T]' is not convertible to 'T' error
}
我想得到类似的东西
func foo(n: String ...) -> String {
return n.joined(separator: ", ")
}
foo(n: "a", "b", "c")
apply(foo, "a", "b", "c") // "a, b, c"
如果可能的话,我想将 fn: (T ...) -> T
的函数签名保持为可变参数,根据需要更改其余部分以适应解决问题的需要。
最佳答案
如果可变参数函数返回与其参数相同的类型(如您的“foo”示例),那么您可以像这样定义应用:
func apply<T>(_ f:(T ...) -> T, with elements:[T]) -> T {
var elements = elements
if elements.count == 0 {
return f()
}
if elements.count == 1 {
return f(elements[0])
}
var result:T = f(elements.removeFirst(), elements.removeFirst())
result = elements.reduce(result, {f($0, $1)} )
return result
}
然后调用它:
func foo(_ n: String ...) -> String {
return n.joined(separator: ", ")
}
func sum(_ numbers:Int ...) -> Int {
return numbers.reduce(0, +)
}
let arrInt = [3, 5, 10]
apply(sum, with: arrInt) // 18
let arrString = ["apple", "peer", "banana"]
apply(foo, with: arrString) // "apple, peer, banana"
关于swift - 如何将数组传递给 Swift 中可变参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56462732/