【问题标题】:Cannot convert value of type '[Int]' to expected argument type 'Int'无法将类型“[Int]”的值转换为预期的参数类型“Int”
【发布时间】: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


【解决方案1】:

由于Int... 在函数体中被视为[Int],因此编译器不允许通过[Int] 代替Int...。您最好按如下方式计算总和,

func makeSomething(_ numbers : Int..., workFunction : (Int...) -> Int) {
    let sum = numbers.map({ workFunction($0)}).reduce(0, +)
    print(sum)
}

或者引入另一个接受Int数组并返回sum的方法。如下,

func anotherSum(_ numbers : [Int]) -> Int {
    return numbers.reduce(0, +)
}

func makeSomething(_ numbers : Int..., workFunction : ([Int]) -> Int) {
    print(workFunction(numbers))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-11
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2017-01-09
    • 2017-02-08
    • 2018-10-01
    相关资源
    最近更新 更多