【问题标题】:Variadic Parameters - Compiler Error cannot convert value of type '[Int]' to expected argument type 'Int'可变参数 - 编译器错误无法将类型“[Int]”的值转换为预期的参数类型“Int”
【发布时间】:2016-02-12 22:12:52
【问题描述】:

Swift 新手。不知道为什么编译器会给出以下代码的错误。:

func addNumbers(numbers: Int ...) -> Int {
    var total : Int = 0
    for number in numbers {
        total += number
    }
    return total
}

func multiplyNumbers(numbers: Int ...) -> Int {
    var total : Int = numbers [0]
    for (index,number) in numbers.enumerate()  {
        if index == 0 {
            continue
        }
        total *= number
    }
    return total
}

func mathOperation(mathFunction: (Int ...) -> Int, numbers: Int ...) -> Int {
     return mathFunction(numbers)
}

错误:

错误:无法将“[Int]”类型的值转换为预期的参数类型 '诠释' 返回数学函数(数字)

【问题讨论】:

  • mathFunction: (Int ...)... 需要一个 single Int 类型的可变参数,而 numbers 是一个 Int 数组;例如,以下签名是有效的(但可能不是您想要的)func mathOperation(mathFunction: ([Int]) -> Int, numbers: Int ...) -> Int { ... }。这可能是出乎意料的,因为mathOperation 中的numbers 是可变参数,但这仅在调用函数时有效:可变参数不是真正的类型,因此一旦numbers 输入“函数的实例” ,它是一个数组。
  • Swift varargs 不像在 Java 中那样容易互换,例如,您不能简单地将数组传入

标签: swift


【解决方案1】:

Swift 可变参数并不那么容易使用。我会将参数类型更改为数组。这是一个有效的修复:

func addNumbers(numbers: [Int]) -> Int {
    var total : Int = 0
    for number in numbers {
        total += number
    }
    return total
}

func multiplyNumbers(numbers: [Int]) -> Int {
    var total : Int = numbers [0]
    for (index,number) in numbers.enumerate()  {
        if index == 0 {
            continue
        }
        total *= number
    }
    return total
}

func mathOperation(mathFunction: [Int] -> Int, numbers: Int ...) -> Int {
     return mathFunction(numbers)
}

print(mathOperation(multiplyNumbers,numbers: 3,24))

这将打印出72

【讨论】:

    【解决方案2】:

    正如 dfri 提到的,可变参数是作为数组类型的,所以它实际上应该是mathFunction: [Int] -> Int, numbers: Int ...)

    编辑:

    由于上述原因,这需要更改 addNumbers 和 multiplyNumbers 的签名以接受[Int]

    【讨论】:

    • 这行不通。您还需要更改其他两个函数的参数。
    • 啊,有道理。
    猜你喜欢
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2021-05-15
    • 2017-01-09
    相关资源
    最近更新 更多