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

I honestly have no idea what this challenge is even asking. Could someone please clarify what we're supposed to solve?

It's asking for a math operation as a parameter, so .. (operation: String)? and then it's asking for 2 Int parameters and an Int return type. So .. (operation: String, a: Int, b: Int) -> Int?

Am I on the write track? This is also a closure course and it just makes the question even more confusing to me, it's probably not as complicated as I'm making it out to be.

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(a: Int, b:Int) -> (Int) {
  return a - b
}

1 Answer

Jared Watkins
Jared Watkins
10,756 Points

The answer is found in the first half of the functions as parameters video. You basically have it right; you're only missing 2 key elements. You can use a function as a parameter just like a: Int and b: Int.

The formatting looks like this:

func mathOperation(mathOpFunc: (Int, Int) -> (Int), a: Int, b: Int) -> Int {

mathOpFunc is an arbitrary parameter name I gave so that the mathOperation function can accept any function. The code reads like this: There's a fun named mathOperation that takes 3 parameters - a function referred to as mathOpFunc that takes two Ints and returns an Int, and a, which is an Int, and b, which is an Int. This mathOperation will return an Int.

so any function that takes to 2 Ints and returns an Int will fulfill the requirements of mathOpFunc: (Int, Int) -> (Int)

The differenceBetweenNumbers function happens to meets those needs perfectly.

finally, within the mathOperation function, we need to say that we want to do what ever function is passed in as a parameter to a and b. It looks like this:

return mathOpFunc(a, b)