Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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)