Variadic Parameters - Compiler Error cannot convert value of type '[Int]' to expected argument type 'Int'

时间:2016-02-12 22:12:52

标签: swift

New to swift. Not sure why the complier is giving the error for the code below.:

Key | FeatureA | FeatureB | FeatureC | FeatureD | FeatureE | FeatureF 
---------------------------------------------------------------------
U1  |        0 |        1 |        0 |        0 |        1 |        0
U2  |        1 |        1 |        0 |        0 |        0 |        1

Error:

error: cannot convert value of type '[Int]' to expected argument type 'Int' return mathFunction(numbers)

2 个答案:

答案 0 :(得分:5)

Swift varargs不太容易使用。我会将参数类型更改为Arrays。这是一个有效的解决方案:

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

答案 1 :(得分:1)

正如dfri所提到的,可变参数被输入为数组,所以实际应该是mathFunction: [Int] -> Int, numbers: Int ...)

编辑:

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