I am a newbie in Swift and I got a compile time error in Playground (highlighted at the "return f(values)" statement):
error: MyPlayground.playground:6:14: error: cannot convert value of type '[Int]' to expected argument type 'Int' return f(values)
The code is as follows:
func max (_ values : Int...) -> Int {
var maxVal : Int = values[0]
for i in values {
if (i > maxVal) {
maxVal = i
}
}
return maxVal
}
func fun (by f:(Int...) -> Int, values:Int... ) -> Int {
return f(values)
}
print(fun(by:max, values:1,2,3,4,5))
What is the error in the code? Thanks for advance.
Edit: The answer "How to forward functions with variadic parameters?" suggested calling another function with array parameter, which I don't really want because there will be extra function call overhead.
My problem is: The code looks syntactically correct, please helps to point out the possible error(s) so I can correct it if encountered in other place. Thanks.
Actually if I replace all "Int..." with "[Int]", everything work fine but the caller statement will be a bit ugly...
Edit 2: As of Swift 4.1 (in Xcode 9.2), the function that forward variadic parameter(s) will IMPLICITLY change it to a single parameter of array of individual parameter(s). To workaround:
func max (_ values : [Int]) -> Int {
var maxVal : Int = values[0]
for i in values {
if (i > maxVal) {
maxVal = i
}
}
return maxVal
}
func fun (by f:([Int]) -> Int, values:Int... ) -> Int {
return f(values)
}
print(fun(by:max, values:1,2,3,4,5))
Don't know whether this is a bug of the compiler or not :)