Back to Swift Reference Ask BeeAI
🔶 Swift LanguageBeginnerSwift 1.0+
Optionals
Represent a value that may be missing, and unwrap it safely with if let, guard let and ??.
An optional is a type that holds either a value or nil. You write it by adding ? to a type: String? means "a String, or nothing".
Swift forces you to unwrap optionals before use. Prefer if let or guard let for safe unwrapping, ?? to provide a default, and optional chaining (?.) to call through values that might be nil.
Since Swift 5.7 you can use the shorthand if let name { } instead of if let name = name { }.
optionals.swift
1struct User {
2 let name: String
3 let nickname: String?
4}
5
6func greeting(for user: User?) -> String {
7 guard let user else { return "Hello, guest" }
8
9 if let nickname = user.nickname {
10 return "Hey \(nickname)!"
11 }
12 return "Hello, \(user.name)"
13}
14
15let count = Int("42") ?? 0 // default value
16let maybeUser: User? = User(name: "Sam", nickname: nil)
17let upper = maybeUser?.nickname?.uppercased() // optional chaining → nilCommon pitfalls
- Avoid force unwrapping (!) outside of tests and truly impossible cases — it crashes at runtime when nil.
- Implicitly unwrapped optionals (String!) are mostly legacy; prefer regular optionals.
Still unclear? Ask BeeAI about Optionals.
Get a tailored explanation, or paste your own code for a Swift 6 review. Free members get daily questions — Pro is unlimited.
Related topics
Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.
See Pro Plans