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 Functions as Parameters

Help me understand this closure logic

I'm reviewing some of the materials outlining closures and there is one part of the logic that seems backwards to me. My last line of code reads displayString(printString) and prints the following:

Printing the string passed in: I'm a function inside another function

From what I understand the printString function stores the displayString's string as aString.

it would at least seem more logical that if you're passing printString to displayString that it would print whatever is in the printString function before the displayString function.

Can anyone elaborate ?

// This function takes a string and prints it
func printString (aString: String) {
    println("Printing the string passed in: \(aString)")
}



func displayString(printStringFunc: (String) -> Void) {
    printStringFunc("I'm a function inside another function")
}


displayString(printString)

1 Answer

Chris Stromberg
PLUS
Chris Stromberg
Courses Plus Student 13,389 Points
// I found the logic really hard to follow with the above example.
// To sum it up, we can pass functions as parameters.
// It might make more sense when using numbers.
func addOneToNumber (number: Int) -> Int {
    return number + 1
}


// This is a function, that takes another function, 
// a function of type "(Int) -> (Int)"
// that is passed in as a parameter 
// and returns an Int.


func addTwoToYourOtherFunction (takeAFunctionAndAddTwo: (Int) -> Int) -> Int {

    return takeAFunctionAndAddTwo(2)
// takes the function you passed in and passes 2 as a parameter to it.
}




// Now take the above function and pass another function of the specified type 
//" (Int) -> (Int) " as a  parameter.

addTwoToYourOtherFunction(addOneToNumber)   // 3