【发布时间】:2019-05-12 01:05:33
【问题描述】:
我是 swift 新手,现在正在努力学习。我写了有参数的函数:数字和使用这个数字的函数:
func anotherSum(_ numbers : Int...) -> Int {
return numbers.reduce(0, +)
}
func makeSomething(_ numbers : Int..., f : (Int...) -> Int) {
print(workFunction(numbers))
}
makeSomething(1,2,3,4,5,6,7,8, f: anotherSum)
但是编译会报错cannot convert value of type '[Int]' to expected argument type 'Int'
。当我试图改变像
workFunction : ([Int]) -> Int) 和
func anotherSum(_ numbers : [Int]) -> Int
它工作得很好,但我仍然不明白为什么用Int... 实现不起作用以及为什么编译器会给出这个错误。
【问题讨论】:
-
就编译器而言,
Int...和[Int]在这种情况下是完全不相关的类型。如果您希望它起作用,您需要修改anotherSum以采用[Int]。目前没有在 Swift 中“分解”数组的方法。 -
Int...会立即在函数体中变成[Int]。anotherSum(Int...)应该有多个参数,而每个参数是一个Int。调用workFunction(numbers)本质上是anotherSum([Int]),你只是传递了一个参数,它是[Int]而不是Int,到anotherSum。这就是类型不匹配的原因。
标签: swift