Error Handling
Result Values
Result stores either a success value or a failure value for later handling.
Store success or failure
result_values.swift
Replay: real traced execution (multi-file project)
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 = 1
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 = 2
let result = lookupName(userId)
let name = try? result.get()
let message = name == nil ? "missing user" : "user=\(name!)"
print(message)
userId ← 1
12let userId→ 1 = 1 //@userId=213let result = lookupName(userId1)14let name = try? result.get()func lookupName(_ id: Int) -> Result<String, LookupError>
5func lookupName(_ id1: Int) -> Result<String, LookupError> {6 if id == 1 {if id == 1
5func lookupName(_ id: Int) -> Result<String, LookupError> {6 if id1 == 1 {7 return Result<String, LookupError>.success("Ada")8 }result ← success("Ada"), name ← Optional("Ada"), message ← user=Ada
12let userId = 1 //@userId=213let result→ success("Ada") = lookupName(userId1)14let name→ Optional("Ada") = try? resultsuccess("Ada").get()15let message→ user=Ada = nameOptional("Ada") == nil ? "missing user" : "user=\(name!)"1617print(messageuser=Ada)outputuser=Ada
userId ← 2
12let userId→ 2 = 213let result = lookupName(userId2)14let name = try? result.get()func lookupName(_ id: Int) -> Result<String, LookupError>
5func lookupName(_ id2: Int) -> Result<String, LookupError> {6 if id == 1 {7 return Result<String, LookupError>.success("Ada")8 }9 return Result<String, LookupError>.failure(LookupError.missing)10}result ← failure(main.LookupError.missing), name ← nil, message ← missing user
12let userId = 213let result→ failure(main.LookupError.missing) = lookupName(userId2)14let name→ nil = try? resultfailure(main.LookupError.missing).get()15let message→ missing user = namenil == nil ? "missing user" : "user=\(name!)"1617print(messagemissing user)outputmissing user
result
`Result` lets code pass an error outcome as data instead of throwing immediately.