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.

Swift
var nickname: String? = nil     // String? can hold nil
nickname = "Lovelace"

// print(nickname.count)  // error: must unwrap first

// if let — unwrap into a new constant if non-nil:
if let nick = nickname {
    print("Called \(nick), \(nick.count) letters")
} else {
    print("no nickname")
}

// Shorthand since Swift 5.7:
if let nickname {
    print(nickname.count)
}

// guard let — unwrap or bail out; great in functions:
func shout(_ word: String?) {
    guard let word else {
        print("nothing to shout")
        return
    }
    print(word.uppercased() + "!")   // 'word' is String here
}
Swift
// Optional chaining — nil short-circuits the chain:
let length = nickname?.count            // Int?

// Nil-coalescing — default when nil:
let display = nickname ?? "anonymous"

// Force unwrap — crashes if nil. Avoid:
// let boom = nickname!.count

let maybeNumber = Int("42")
print(maybeNumber ?? 0)                 // 42
⚠ 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.
✦ 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.