Tuesday, July 31, 2018

The Swift Compiler Can Reason About “Never”

Mattt Thompson:

By specifying Never as the result’s Error type, we’re using the type system to signal that failure is not an option. What’s really cool about this is that Swift is smart enough to know that you don’t need to handle .failure for the switch statement to be exhaustive:

alwaysSucceeds { (result) in
    switch result {
    case .success(let string):
        print(string)
    }
}

You can see this effect played out to its logical extreme in the implementation conforming Never to Comparable:

extension Never: Comparable {
  public static func < (lhs: Never, rhs: Never) -> Bool {
    switch (lhs, rhs) {}
  }
}

Comments RSS · Twitter

Leave a Comment