Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Closures Functions as First Class Citizens Higher Order Functions

Sumit Pandey
Sumit Pandey
2,252 Points

[Solved] Question with the task in swift closures.

My Solution: let difference = mathOperation(differenceBetweenNumbers, 15, 10)

However, it keeps giving me an error. The code seems to run fine in playground and returns 5 as the answer.

Thanks in advance!

higherOrderFunctions.swift
/** 
  For this code challenge, let’s define a math operation as a function that 
  carries out some work on two integers and returns an integer as well. An 
  example is the function below, `differenceBetweenNumbers`, which takes two 
  integers and calculates the difference between the numbers. After calculating, 
  it returns the difference.
*/

func differenceBetweenNumbers(a: Int, b:Int) -> (Int) {
  return a - b
}

// Enter your code below
func mathOperation(operation:(Int, Int)->(Int), a: Int, b: Int) -> (Int){ 
  return operation(a,b)
}

let difference = mathOperation(differenceBetweenNumbers, 15, 10)

3 Answers

Jhoan Arango
Jhoan Arango
14,575 Points

You are forgetting to use your named parameters when calling the function.

let difference = mathOperation(differenceBetweenNumbers, a: 15, b: 10)

// Try it like this and see if it passes.
Sumit Pandey
Sumit Pandey
2,252 Points

Hi Jhoan,

Thanks for replying, I just tried it with the named parameters but that gives me the following response: Bummer! Make sure your function is named mathOperation and check your parameters and return type!

and the following error in the preview page: swift_lint.swift:20:31: error: extraneous argument labels 'a:b:' in call let difference = mathOperation(differenceBetweenNumbers, a: 15, b: 10) ^ ~~~ ~~~

Here is what I get once I remove the named parameters:
Bummer! Make sure you are computing the difference between two integers using the functions created and assigning the result to a constant named difference.

Thanks again.

Jhoan Arango
Jhoan Arango
14,575 Points

Ok, I see your error.. Try this.

func mathOperation(operation:(Int, Int)->(Int), a: Int, b: Int) -> Int { 
  return operation(a,b)
}

Let me know if that works. I think someone had asked me this same question before and they had the same issue.

Sumit Pandey
Sumit Pandey
2,252 Points

Thanks so much. This works perfectly.

But this is such a weird error :)