An Optional is a type that either holds a value or holds nil (no value). Swift makes nil explicit in the type system: String can never be nil, but String? can. This is how Swift eliminates most null-pointer crashes at compile time.
An Optional is a type that either holds a value or holds nil (no value). Swift makes nil explicit in the type system: String can never be nil, but String? can. This is how Swift eliminates most null-pointer crashes at compile time.
Under the hood Int? is an enum with two cases: .some(value) or .none. You cannot use the wrapped value directly — you must unwrap it first.
var name: String? = "Ada" // Optional String, currently .some("Ada")
var missing: String? = nil // .none
// if let: bind only when non-nil, scoped to the block
if let name = name {
print(name.count) // safe: name is a plain String here
}
// guard let: unwrap or exit early — keeps the happy path un-nested
func greet(_ input: String?) {
guard let input else { return } // Swift 5.7 shorthand
print("Hi \(input)") // input is non-optional below
}
// nil-coalescing: supply a default
let display = name ?? "Anonymous"
The ! operator force-unwraps: name! crashes if name is nil. Use it only when a value is guaranteed by program logic — otherwise prefer if let, guard let, or ??.
let url = URL(string: "https://a.com")! // OK: literal is always valid
let user = fetchUser()! // BAD: crashes on nil
String!) crash silently when accessed while nil — common with @IBOutlet.user?.address?.city short-circuits to nil instead of crashing.Optionals encode "this might be absent" in the type, so the compiler forces you to handle the empty case. Interviewers use this to see whether you reach for guard let and ?? instead of sprinkling !, which is the difference between a crash-prone app and a safe one.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate