Skip to content
Optionals
step 1/5

Reading — step 1 of 5

Learn

~1 min readStrings and Optionals

Optionals are Swift's answer to null. A type T cannot hold nil; T? (Optional<T>) can.

var name: String = "Alice"
var maybeName: String? = nil   // legal — String? can be nil

// name.count       // ✓ — String is non-optional
// maybeName.count  // ✗ compile error

Three main ways to use an optional:

// Optional binding (most common)
if let actualName = maybeName {
    print(actualName.count)   // actualName is non-optional inside the if
}

// Nil-coalescing operator
let length = maybeName?.count ?? 0

// Force unwrap (crashes on nil)
let length2 = maybeName!.count

guard let is the inverse of if let — early-return when nil. It's idiomatic at the top of functions to peel off optional inputs.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Optionals — Swift Fundamentals