LESSON 2 OF 6

Optionals and safe code

Treat missing values as part of your model.

A value can be absent

String? means either a String or nil. Optionality is useful for genuinely missing data: a search that found no item, a field omitted by an API, or a parsing operation that failed.

Unwrap intentionally

if let gives you a non-optional value inside its block. guard let is useful when the remaining function needs that value; its else branch must leave the current scope. The ?? operator provides a fallback.

Avoid hiding failures

A force unwrap can trap when the value is nil. A default can also hide a data problem. Choose whether missing data should be ignored, displayed as a fallback, or reported as an error.

Try it yourself

main.swift
let name: String? = "Sam"
if let name { print("Hello, \(name)") }
let missing: String? = nil
print(missing ?? "Anonymous")

Avoid force unwrapping unless an invariant guarantees the value exists.

Continue with the official Swift language guide