Skip to content

Instantly share code, notes, and snippets.

@dfrobison
Created February 4, 2020 03:40
Show Gist options
  • Save dfrobison/e4023ac1353c9c69aa3fa59b7a8a90b6 to your computer and use it in GitHub Desktop.
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/)
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