Lesson 2 of 9 · 23m
Optionals, Errors, and Boundary Design
Use optionals and typed failures to make absence, validation, and recoverability explicit instead of hiding them behind crashes and sentinel values.
Most crashes attributed to Swift are not really Swift failures. They are boundary failures: the developer assumed a response, file, default, or platform object would exist because it existed on their device that afternoon. Optionals and errors force you to say the uncomfortable part out loud.
Optional means absence, not inconvenience
An optional should represent legitimate absence. If a value must exist for a feature, validate it once at the boundary and pass forward a non-optional model:
struct InviteAcceptanceRequest {
let inviteID: UUID
let displayName: String
init?(payload: [String: Any]) {
guard let rawID = payload["invite_id"] as? String,
let inviteID = UUID(uuidString: rawID),
let name = payload["display_name"] as? String,
!name.isEmpty else { return nil }
self.inviteID = inviteID
self.displayName = name
}
}Inside the feature, the code no longer carries five guards and three force unwraps. The ugly truth stays at the edge where untrusted input arrives.
Force unwrapping is a claim you may be wrong about
value!, try!, and as! are valid only when the invariant is controlled by your process and preferably covered by tests. They are not a strategy for user input, network data, files, dates, or platform callbacks:
let bundled = Data(base64Encoded: checkedInTemplate)!
let remoteDate = ISO8601DateFormatter().date(from: serverString)!The first line may be defensible. The second is a crash decision delegated to the server.
Errors should carry recovery meaning
A giant AppError with thirty unrelated cases is barely better than NSError(domain: "oops", code: 1). Define errors near the operation that throws them:
enum InviteError: LocalizedError, Equatable {
case expired
case alreadyAccepted
case networkUnavailable
case serverRejected(reason: String)
var errorDescription: String? {
switch self {
case .expired: "This invitation has expired."
case .alreadyAccepted: "This invitation was already accepted."
case .networkUnavailable: "You appear to be offline."
case .serverRejected(let reason): reason
}
}
}Now the caller can retry, sign out, ask for input, or show a dead-end message. Catch-all print(error) is not handling; it is postponing a user-visible failure until nobody can reconstruct it.
Validate once, transform once
Use this boundary shape:
external JSON -> DTO -> validated input -> domain model -> UI stateDTOs model the wire. Domain models model the business. UI state models what is rendered. When one struct plays all three roles, every backend typo becomes an app refactor.
Field notes
niland failure are different. Missing optional metadata is not the same as a failed request.- Empty strings, zero, and magic dates make poor sentinels because they leak into comparisons and analytics.
LocalizedErrortext is user-facing copy, not a debug log.- Removing force unwraps helps because the underlying boundary assumption is finally handled, not because the exclamation point was unlucky.
Was this lesson helpful?