Alex Does Things Poorly

Alex does a variety of things poorly - swift, data science, datavis, ML, drawing, AR, unity, etc, etc.

14 February 2020

Closures, part 1

by alex

Today I’m continuing to day 6 of 100 Days of Swift. Today we’re back on closures. I use closures a lot in Swift and Objective-C, but mostly by recipe. This recipe/copypasta code is exactly what I’m trying to get past with 100 Days of Swift, so let’s dig in.

I noticed today that the basic closure syntax () -> Void literally means “takes an empty tuple of arguments and returns nothing.” It’s not magic syntax, it’s actually got meaning. Funny how that never really occurred to me before.

Also something to note is that while functions take parameter labels, closures do not.

Finally, trailing closure syntax is pretty elegant and cool.

func uploadObservation(taxon: String, uploadProgress: (Double) -> Void) {
    var pctDone: Double = 0
    repeat {
        uploadProgress(pctDone)
        pctDone += 0.1
    } while pctDone < 1
}

uploadObservation(taxon: "Boletus rubriceps") { pctDone in
    print("upload progress is \(pctDone)")
    
    DispatchQueue.main.async {
        // update a progress bar
    }
}

Finally, today’s annoyance: why don’t print statements inside closures show up as string output in the Swift Playgrounds for iPad output viewer? It makes debugging hard. The lack of a console output viewer is frustrating in Playgrounds , debugging order of operations is basically impossible.

Also, related to my complaint about Ulysses auto-capitalizing text in code blocks: why does Ulysses autocorrect spelling in code blocks?

Test edit

tags: