BeginnerLesson 6 of 16
Optionals – Swift
Swift's answer to null: a value is present or nil, enforced by the compiler.
An optional (T?) is either a value or nil. It is a type of its own: Int? is not Int. The compiler forces you to handle the missing case before you use the value. This largely consigns null-pointer crashes to the past.
var name: String? = "Ada"
name = nil // allowed, because it is optional
let zahl = Int("42") // type: Int?
print(zahl as Any) // Optional(42)
// Unwrap safely: if let
if let z = zahl {
print("Number", z + 1) // Number 43
} else {
print("no number")
}
// Default value: ??
let wert = Int("abc") ?? -1
print(wert) // -1guard let unwraps and leaves the function early if the value is missing. The unwrapped name is then available in the entire rest of the block, which keeps the code flat and readable.
func gruss(_ name: String?) {
guard let name else { // shorthand since Swift 5.7
print("No name")
return
}
print("Hello \(name)")
}
gruss("Ada") // Hello Ada
gruss(nil) // No name
func findeIndex(_ liste: [String], _ ziel: String) -> Int? {
liste.firstIndex(of: ziel)
}
if let i = findeIndex(["a", "b", "c"], "b") { print("Index", i) } // Index 1Optional chaining (?.) calls properties and methods only if the value exists; otherwise the result is nil. With map you transform the content without unwrapping.
struct Adresse { var stadt: String }
struct Person {
var name: String
var adresse: Adresse?
}
let ada = Person(name: "Ada", adresse: Adresse(stadt: "London"))
let bob = Person(name: "Bob", adresse: nil)
print(ada.adresse?.stadt ?? "unknown") // London
print(bob.adresse?.stadt ?? "unknown") // unknown
let vorname: String? = "Ada"
print(vorname.map { $0.count } ?? 0) // 3
print(vorname?.uppercased() ?? "") // ADATipWith
?? you can build chains (a ?? b ?? "Default"). if let a, let b { ... } unwraps several optionals at once; if let x = x, x > 5 adds an extra condition.WarningThe exclamation mark
x! (force unwrap) crashes on nil. Only use it when nil is truly impossible and you can justify that; when in doubt, use if let, guard let, or ??. String! (implicitly unwrapped) is also a crash risk.