In this presentation—given at Appdevcon march 2019—we take a closer look at Swift 5’s result type and how this functional programming paradigm compares to “regular” imperative error handling.
static var errorDomain: String { return "com.impendingdoom" } /// The error code within the given domain. var errorCode: Int { return 500 } /// The user-info dictionary. var errorUserInfo: [String : Any] { return ["Oh no" : "We are doomed"] } }
{ (data, response, error) -> Void in if let data = data, error == nil { store(data: data) } else if let error = error { handle(error: error) } else { // both data and error are nil, what now? fatalError("Shouldn't come here ") } } task.resume()
{ (data, response, error) -> Void in if let data = data, error == nil { store(data: data) } else if let error = error { handle(error: error) } else { // both data and error are nil, what now? fatalError("Shouldn't come here ") } } task.resume()
{ (data, response, error) -> Void in if let data = data, error == nil { store(data: data) } else if let error = error { handle(error: error) } else { // both data and error are nil, what now? fatalError("Shouldn't come here ") } } task.resume()
{ (data, response, error) -> Void in if let data = data, error == nil { store(data: data) } else if let error = error { handle(error: error) } else { // both data and error are nil, what now? fatalError("Shouldn't come here ") } } task.resume()
enum Result<Value, Failure> { case success(Value) case failure(Failure) } enum Result<Value> { case success(Value) case error(NSError) case canceled } enum Result<Value> { case success(Value) case failure(Error) }
A success, storing a `Success` value. case success(Success) /// A failure, storing a `Failure` value. case failure(Failure) // ... rest omitted } public enum Optional<Wrapped> { case none case some(Wrapped) }
{ (data, response, error) -> Void in if let data = data, error == nil { store(data: data) } else if let error = error { handle(error: error) } else { // both data and error are nil, what now? fatalError("Shouldn't come here ") } } task.resume()
{ if temperature < 100 { return Result.failure(BakingError.rawPancake) } else if temperature > 300 { return Result.failure(BakingError.burntPancake) } else if temperature > 500 { return Result.failure(CookingError.kitchenFire) } let pancake = Pancake() return Result.success(pancake) }