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
enum ParseError: Error {
case notNumber
}
func parseCount(_ text: String) throws -> Int {
if let value = Int(text) {
return value
}
throw ParseError.notNumber
}
let rawCount =
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 =
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 =
let count = try? parseCount(rawCount)
let label = count == nil ? "missing" : "count=\(count!)"
print(label)
try optional
`try?` is useful when a missing value is enough information for the caller.