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 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