Day 6 – Closures Part One

// closures

/// basic closures

let driving = {
    print("I'm driving!")


/// parameters in closures

let biking = { (place: String) in
    print("I'm going to \(place) on my bike.")

biking("Torino") // no parameter labels in closures

/// returning values

let pedaling = { (place: String) -> String in
    return "I'm pedaling to \(place)! Also watch out for this return value."

let message = pedaling("Milano")

/// closures as parameters

func travel(action: () -> Void) { //() symbolises the function, Void is no return
    print("I'm about to run the closure.")
    print("Nicely done.")

travel(action: driving)

/// trailing closure syntax
//// when the last parameter we pass to a function is a closure, we can use
//// this special type of syntax to simplify things when we CALL it (not when
//// we create it!

travel {

//// here, we called the function travel, and immediately gave it its only
//// parameter, the closure. We can put any code in between those two
//// curly brackets and it will be interpreted as the closure parameter.

Leave a Reply

Your email address will not be published. Required fields are marked *