3
votes

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)

2
mathFunction: (Int ...)... expects a variadic argument of single Int types, whereas numbers is an Int array; e.g., the following signature is valid (but perhaps not as you intended) func mathOperation(mathFunction: ([Int]) -> Int, numbers: Int ...) -> Int { ... }. This is possibly unexpected as numbers in mathOperation is a variadic parameter, but this is only in effect when calling the function: variadic parameters aren't really a type, so once numbers enter "an instance of the function", it's an array. - dfrib
Swift varargs are not as easily interchangeable as in Java for example, you cannot simply pass an array in - luk2302

2 Answers

5
votes

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

1
votes

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.