root@coding-prodigies:~# โ–Š
// lesson 3 of 11 ยท 18 min

Optionals

โš‘ Report an issue with this lesson
var subtitle: String? = nil

if let unwrapped = subtitle {
    print(unwrapped)
} else {
    print("No subtitle")
}

let length = subtitle?.count ?? 0 // nil-coalescing, defaults to 0

An optional (String?) either holds a value or nil -- the compiler forces you to unwrap it before use, so "unexpectedly found nil" crashes become compile-time errors instead of runtime surprises.

Optional chaining lets you drill through several optional links at once, short-circuiting to nil the moment any link is nil:

struct Address {
    var city: String?
}
struct Student {
    var address: Address?
}

let student: Student? = getStudent()
let city = student?.address?.city
// city is String? -- nil if student is nil, or address is nil,
// or city itself was nil; no crash at any step

Force-unwrapping with ! tells the compiler "I guarantee this isn't nil" -- and crashes immediately with "Fatal error: Unexpectedly found nil" if you're wrong:

let subtitle: String? = fetchSubtitle()
let length = subtitle!.count // crashes here if subtitle is actually nil

Force-unwrapping should be rare in reviewed code -- reach for it only when nil is truly impossible by construction (for example, right after you just checked if subtitle != nil in the same scope, though even then if let is preferred since it doesn't require a second unwrap). guard let is the idiomatic way to unwrap and exit early when a value is missing, which keeps the "happy path" unindented:

func printSubtitle(_ subtitle: String?) {
    guard let subtitle = subtitle else {
        print("No subtitle")
        return
    }
    // subtitle is a non-optional String for the rest of this function
    print(subtitle)
}

Implicitly unwrapped optionals (String!) behave like a regular optional for assignment but auto-unwrap on use, crashing on nil just like ! would -- they exist mainly for interoperating with Objective-C APIs and legacy patterns like @IBOutlet, and are rarely the right choice in new Swift code.

Try it yourself

Exercise: Make subtitle an optional String and print it safely with if-let.
Expected output:
No subtitle
swift
Output

      
    

Run your code and get it working before marking this lesson complete.

// that was the last free lesson

8 more lessons โ€” including Capstone project: a course catalog โ€” plus a certificate are waiting.

Unlock the full course โ€” $149.99