Closures, Part 2

I’ve done a full week of 100 Days of Swift, which means I’m 7% of the way done, right?

Today was more brain twisting closures. Happily I feel like I grok them a little better today than I did a week ago, so that’s progress. Two things stand out to me as new things I learned today: shorthand closure syntax and capturing values.

I’d come across the $0 syntax once or twice but I hadn’t known how much boilerplate could be removed in trailing closure calling syntax. You can even remove the return statement in a one line closure block:

func eatSushi(action: (String) -> String) {
    let description = action("Salmon")
    print(description)
}
eatSushi { (food: String) -> String in
    return "I'm noshing on some \(food)"
}
eatSushi {
    return "I'm eating up some \($0)"
}
eatSushi {
    "I'm almost full of \($0)"
}

Another thing that I knew was possible was capturing values in a closure. I’d come across it in javascript, and it’s also just part of the definition, that a closure captures values that are used locally but are defined in an enclosing/outer scope. Anyways, cool to see the syntax explicitly laid out in Swift:

func readComic() -> (String) -> Void {
    var comicsRead = 0
    return {
        comicsRead += 1
        print("After reading \($0), you've read \(comicsRead) comics.")
    }
}
let reader = readComic()
reader("The Girl from H.O.P.P.E.R.S")
reader("Transmetropolitan")
reader("King City")
reader("Black Monday Murders")

Now off to work on MFArtist a little bit!