Dear Erica: How do you create `Never` callbacks?

Vivien Leroy writes: I tried using Never for my API module callbacks but couldn’t really figure out how to use it when my callbacks contains guards. Here’s an example:

Capture d’écran 2016-09-06 à 17.15.59

Do you have any hints on how to properly use Never for such case?

While you don’t really need a Never return type for completion methods, especially those that don’t exit the application, you can work around guard conditions by skillful use of do clauses.

You might create a Never-based completion type:

typealias CompletionNever = () -> Never

func functionWithNeverCompletion(completion: CompletionNever) 
{
    // ... do interesting things ...
    completion()
}

Guard conditions require you to exit scope. Never mean you cannot  return from your function. So, instead, add a simple do-scope layer:

functionWithNeverCompletion {
    alldone: do {
        guard somecondition else { break alldone }
        print("Hello")
    }
}

This ensures you can perform all the standard guard conditions, including Boolean tests, optional binding, availability checks, and so forth, while maintaining the “no return” integrity of the handler.

Comments are closed.