SwSwift · Lesson 2 of 8
Optionals
Swift's answer to null crashes: a value that might be absent has a different type — String? instead of String — and the compiler forces you to handle the absence before using it.
⚠ Warning
The ! operator means 'crash if this is nil'. In app code there's nearly always a better shape: if let, guard let, ?? or ?. — reserve ! for cases where nil is provably impossible, and expect reviewers to question every one.
The ! operator means 'crash if this is nil'. In app code there's nearly always a better shape: if let, guard let, ?? or ?. — reserve ! for cases where nil is provably impossible, and expect reviewers to question every one.
✦ Tip
guard let is the idiomatic Swift function opener: check requirements at the top, exit early if unmet, and the rest of the function works with clean non-optional values. Deeply nested if-lets are a smell.
guard let is the idiomatic Swift function opener: check requirements at the top, exit early if unmet, and the rest of the function works with clean non-optional values. Deeply nested if-lets are a smell.