Shivam Sinha
Shivam Sinha

Reputation: 5150

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

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

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)
}

Error:

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

Upvotes: 3

Views: 993

Answers (2)

kevchoi
kevchoi

Reputation: 434

As dfri mentioned, the variadic parameters are typed as arrays, so it should actually be mathFunction: [Int] -> Int, numbers: Int ...)

EDIT:

This requires changing the signature of addNumbers and multiplyNumbers to take in [Int], because of the reason above.

Upvotes: 1

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23512

Swift varargs aren't quite as easy to work with. I would change the parameter types to Arrays. Here's a working fix:

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))

This will print out 72

Upvotes: 5

Related Questions