Optionals intro: ?, nil, if let, guard let, ??
Introduce optionals: declaring with ?, representing missing values with nil, and unwrapping via if let, guard let, and ??
What is an Optional?
Optionals represent a value that may be present or nil. Add ? to a type to make it optional.
- Handle absence explicitly
- Avoids many crashes
if let binding
Declare with ?, then use if let to unwrap safely when present.
var nickname: String? = nil
print("nickname =", String(describing: nickname))
// Optional binding with if let
let input: String? = "Ada"
if let name = input {
print("Hello, \\(name)")
} else {
print("No name")
}All lessons in this course
- let vs var, type inference, literals, tuples
- Core types: numbers, Bool, String, Character
- Optionals intro: ?, nil, if let, guard let, ??