Error Handling
Try Optional
try? turns a thrown error into nil so the caller can branch with optionals.
Convert failure to nil
try_optional.swift
Replay: real traced execution (multi-file project)
enum ParseError: Error {
case notNumber
}
func parseCount(_ text: String) throws -> Int {
if let value = Int(text) {
return value
}
throw ParseError.notNumber
}
let rawCount = "12"
let count = try? parseCount(rawCount)
let label = count == nil ? "missing" : "count=\(count!)"
print(label)
enum ParseError: Error {
case notNumber
}
func parseCount(_ text: String) throws -> Int {
if let value = Int(text) {
return value
}
throw ParseError.notNumber
}
let rawCount = "bad"
let count = try? parseCount(rawCount)
let label = count == nil ? "missing" : "count=\(count!)"
print(label)
enum ParseError: Error {
case notNumber
}
func parseCount(_ text: String) throws -> Int {
if let value = Int(text) {
return value
}
throw ParseError.notNumber
}
let rawCount = "4"
let count = try? parseCount(rawCount)
let label = count == nil ? "missing" : "count=\(count!)"
print(label)
rawCount ← 12
12let rawCount→ 12 = "12" //@rawCount="bad", "4"13let count = try? parseCount(rawCount12)14let label = count == nil ? "missing" : "count=\(count!)"func parseCount(_ text: String) throws -> Int
5func parseCount(_ text12: String) throws -> Int {6 if let value = Int(text) {if let value = Int(text)
5func parseCount(_ text: String) throws -> Int {6 if let value12 = Int(text12) {7 return value128 }count ← Optional(12), label ← count=12
12let rawCount = "12" //@rawCount="bad", "4"13let count→ Optional(12) = try? parseCount(rawCount12)14let label→ count=12 = countOptional(12) == nil ? "missing" : "count=\(count!)"1516print(labelcount=12)outputcount=12
rawCount ← bad
12let rawCount→ bad = "bad"13let count = try? parseCount(rawCountbad)14let label = count == nil ? "missing" : "count=\(count!)"func parseCount(_ text: String) throws -> Int
5func parseCount(_ textbad: String) throws -> Int {6 if let value = Int(text) {7 return value8 }9 throw ParseError.notNumber10}count ← nil, label ← missing
12let rawCount = "bad"13let count→ nil = try? parseCount(rawCountbad)14let label→ missing = countnil == nil ? "missing" : "count=\(count!)"1516print(labelmissing)outputmissing
rawCount ← 4
12let rawCount→ 4 = "4"13let count = try? parseCount(rawCount4)14let label = count == nil ? "missing" : "count=\(count!)"func parseCount(_ text: String) throws -> Int
5func parseCount(_ text4: String) throws -> Int {6 if let value = Int(text) {if let value = Int(text)
5func parseCount(_ text: String) throws -> Int {6 if let value4 = Int(text4) {7 return value48 }count ← Optional(4), label ← count=4
12let rawCount = "4"13let count→ Optional(4) = try? parseCount(rawCount4)14let label→ count=4 = countOptional(4) == nil ? "missing" : "count=\(count!)"1516print(labelcount=4)outputcount=4
try optional
`try?` is useful when a missing value is enough information for the caller.