You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Optionals are one of Swift's most important safety features. An optional represents a value that might be absent. This lesson covers optional types, unwrapping techniques, and best practices.
An optional is a type that can hold either a value or nil (no value):
var name: String? = "Alice" // has a value
var age: Int? = nil // no value
// Without the ?, the type cannot be nil
// var greeting: String = nil // Error: 'nil' cannot be assigned to type 'String'
Under the hood, Optional<T> is an enum:
enum Optional<Wrapped> {
case none // nil
case some(Wrapped) // a value
}
In many languages, any reference can be null, leading to runtime crashes. Swift makes the possibility of absence explicit in the type system:
| Language | Null handling | Safety |
|---|---|---|
| Swift | Optional<T> — explicit in the type | Compile-time checked |
| Java | Any reference can be null | Runtime NullPointerException |
| JavaScript | undefined and null | Runtime TypeError |
| Kotlin | T? nullable types | Compile-time checked |
| Rust | Option<T> | Compile-time checked |
The safest and most common way to unwrap:
let possibleNumber = "123"
if let number = Int(possibleNumber) {
print("The number is \(number)")
} else {
print("Not a valid number")
}
let name: String? = "Alice"
if let name {
print("Hello, \(name)") // 'name' is now non-optional
}
For early exits when a value is missing:
func process(input: String?) {
guard let input else {
print("No input provided")
return
}
// 'input' is non-optional for the rest of the function
print("Processing: \(input)")
}
Provide a default value when an optional is nil:
let userColour: String? = nil
let colour = userColour ?? "Blue" // "Blue"
// Chainable
let primary: String? = nil
let secondary: String? = nil
let fallback = primary ?? secondary ?? "Default"
Safely access properties, methods, and subscripts on optionals:
struct Address {
var street: String
var city: String
}
struct Person {
var name: String
var address: Address?
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.