Optionals are one of Swift's most important features. An optional represents a value that may or may not exist. In Swift, you must explicitly handle the possibility of nil before using an optional value.
Swift
Beginner
10 min read
Optionals in Swift
Example
// Declaring optionals
var username: String? = "alice"
var score: Int? = nil
// Optional binding (if let)
if let name = username {
print("User: \(name.uppercased())")
} else {
print("No user")
}
// Guard let (early exit pattern)
func processUser(_ name: String?) -> String {
guard let name = name, !name.isEmpty else {
return "Invalid user"
}
return "Processing \(name)"
}
// Nil coalescing ??
let displayName = username ?? "Guest"
print(displayName)
// Optional chaining ?.
struct User {
var address: Address?
}
struct Address {
var city: String
}
var user: User? = User(address: Address(city: "Tokyo"))
print(user?.address?.city ?? "Unknown") // "Tokyo"
// Force unwrapping ! (use with caution)
let definiteValue: String! = "I'm definitely not nil"
print(definiteValue)