Articles, podcasts and news about Swift development, by John Sundell.

Using "then" as an external parameter label for closures

Published on 20 Feb 2018
Basics article available: Closures

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
    ...
})

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: If you want to become a complete senior iOS developer, join this free online crash course starting on October 18th. Learn how to apply truly scalable iOS app architecture patterns through a series of lectures and practical coding sessions. Click to learn more.