Error Handling
Result Values
Result stores either a success value or a failure value for later handling.
Store success or failure
result_values.swift
enum LookupError: Error {
case missing
}
func lookupName(_ id: Int) -> Result<String, LookupError> {
if id == 1 {
return Result<String, LookupError>.success("Ada")
}
return Result<String, LookupError>.failure(LookupError.missing)
}
let userId =
let result = lookupName(userId)
let name = try? result.get()
let message = name == nil ? "missing user" : "user=\(name!)"
print(message)
enum LookupError: Error {
case missing
}
func lookupName(_ id: Int) -> Result<String, LookupError> {
if id == 1 {
return Result<String, LookupError>.success("Ada")
}
return Result<String, LookupError>.failure(LookupError.missing)
}
let userId =
let result = lookupName(userId)
let name = try? result.get()
let message = name == nil ? "missing user" : "user=\(name!)"
print(message)
result
`Result` lets code pass an error outcome as data instead of throwing immediately.