如何将数组传递给 Swift 中可变的函数?

How to pass an array to a function which is variadic in Swift?

如何将数组传递给可变参数的函数?

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 的函数签名保留为可变参数,根据需要更改其余部分以适应问题。

提供可变参数函数 returns 与其参数类型相同(如您的 '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([=10=], )} )

   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"