Reading — step 1 of 6
Learn
~1 min readOptionals and Errors
Swift error handling is explicit but not exception-based. A function that can fail is marked throws; callers must use try.
enum ValidationError: Error {
case empty
case tooShort(min: Int)
case invalidFormat
}
func validate(_ s: String) throws -> String {
if s.isEmpty { throw ValidationError.empty }
if s.count < 3 { throw ValidationError.tooShort(min: 3) }
return s
}
Calling throwing functions — three forms:
// 1. try ... catch — propagate or handle
do {
let valid = try validate(input)
use(valid)
} catch ValidationError.empty {
print("empty")
} catch ValidationError.tooShort(let min) {
print("need at least \(min)")
} catch {
print("unknown: \(error)") // bare catch — error is implicit
}
// 2. try? — convert to Optional, nil on error
let maybe: String? = try? validate(input)
// 3. try! — force, crashes on error
let definitely = try! validate(input)
Errors are types (any type that conforms to Error protocol). Enums are the idiomatic choice — give callers a finite set of cases to match on.
Re-throwing: a function with a closure parameter that throws can be marked rethrows. The function only throws if the closure does.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…