Optionals are one of the most important concepts in Swift. An optional is a safe way to handle data that might have a value — or might not. The absence of a value is called nil.
There are plenty of cases where data might be missing — API responses, form input, dictionary lookups, user profile images, and more. Optionals let you handle those cases systematically without crashing.
swift
var displayName: String? = "Sai Tun"
if let name = displayName {
print("Hello, \(name)")
} else {
print("Hello, guest")
}
let fallbackName = displayName ?? "Guest"
print("Profile: \(fallbackName)")String? means the value could be a string, or it could be nil.if let only assigns to name when the optional actually has a value. ?? gives you a fallback value in case it's nil.
You should see
Hello, Sai Tun Profile: Sai Tun