3

I new in swift and now learning this hard as i can. I wrote function that got arguments: numbers and function that work with this numbers:

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) 

But compile gives out error cannot convert value of type '[Int]' to expected argument type 'Int' . When i tried to change argument like

workFunction : ([Int]) -> Int) and

func anotherSum(_ numbers : [Int]) -> Int

It work perfectly, but i still can't understand why realisation with Int... doesn't work and why compiler gives this error.

2
  • 1
    As far as the compiler is concerned, Int... and [Int] are completely unrelated types in this context. You need to modify anotherSum to take a [Int] instead, if you want this to work. There's no current way to "splat" arrays in Swift. Commented Dec 11, 2018 at 4:31
  • 1
    Int... will turn into [Int] immediately in the function body. anotherSum(Int...) is supposed to take multiple parameters, while each parameter is an Int. Calling workFunction(numbers) is essentially anotherSum([Int]), you've just passed a single parameter, which is [Int] not Int, to anotherSum. That's why types do not match. Commented Dec 11, 2018 at 4:37

1 Answer 1

4

As the Int... is considered as an [Int] in the function body so compiler will not allow to pass [Int] in place of Int.... You better calculate the sum as below,

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

Or introduce another method that accepts array of Int and returns sum. Something as below,

func anotherSum(_ numbers : [Int]) -> Int { return numbers.reduce(0, +) } func makeSomething(_ numbers : Int..., workFunction : ([Int]) -> Int) { print(workFunction(numbers)) } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.