Weekly Swift articles, podcasts and tips by John Sundell.

Using "then" as an external parameter label for closures

Published on 20 Feb 2018

I've started using "then" as an external parameter label for completion handlers. Makes the call site read really nicely (Because I do love conversational API design) regardless of whether trailing closure syntax is used or not.

protocol DataLoader {
    // Adding type aliases to protocols can be a great way to
    // reduce verbosity for parameter types.
    typealias Handler = (Result<Data>) -> Void
    associatedtype Endpoint

    func loadData(from endpoint: Endpoint, then handler: @escaping Handler)
}

loader.loadData(from: .messages) { result in
    ...
}

loader.loadData(from: .messages, then: { result in
    ...
})