Lesson 2 of 8

Optionals

Learn optionals, Swift's way of handling values that might be missing. A ? is a different type from a String, and the makes you handle the missing case before you use 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
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.