Created
February 4, 2020 03:40
-
-
Save dfrobison/e4023ac1353c9c69aa3fa59b7a8a90b6 to your computer and use it in GitHub Desktop.
[Result’s convenience APIs] from John Sundell (https://www.swiftbysundell.com/tips/result-type-convenience-apis/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let data: Data = ... | |
let decoder = JSONDecoder() | |
// This will create a Result<Model, Error> instance, which will contain | |
// 'success' if its expression succeeded, and 'failure' if it ended | |
// up throwing an error: | |
let result = Result { | |
try decoder.decode(Model.self, from: data) | |
} | |
// The above API is really useful when we want to return a Result | |
// value from an asynchronous operation, for example by calling | |
// a completion handler: | |
completionHandler(result) | |
func decode(_ result: Result<Data, Error>) throws -> Model { | |
// Using Result's 'get' method, we can either extract its | |
// underlying value, or throw any error that it contains: | |
let data = try result.get() | |
let decoder = JSONDecoder() | |
return try decoder.decode(Model.self, from: data) | |
} | |
let dataResult: Result<Data, Error> = ... | |
let stringResult = dataResult.map { | |
String(decoding: $0, as: UTF8.self) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment