Optionals
A regular type like String can never hold nil — the compiler guarantees it. To allow 'no value', you write the type with a trailing ? — String? — making it an optional. Everywhere else on this site that covers null safety (Kotlin's String?, C#'s int?), the idea is the same: the possibility of absence becomes part of the type itself, not something that can sneak in unannounced.
if let safely unwraps an optional only inside the block where it succeeds. guard let does the opposite: it unwraps for the rest of the current scope, exiting early (with return, in a function) if the value is nil — useful for handling the 'no value' case up front and letting the rest of the function assume a real value exists.
func describe(_ name: String?) -> String {
guard let n = name else {
return "no name"
}
return "Hello, \(n)"
}
print(describe(nil))
print(describe("Swift"))no name Hello, Swift
What a real optionals error looks like
Assigning nil to a plain, non-optional type isn't a warning — it's a compile error, and Swift's compiler is specific about the fix. This is genuinely what the compiler reports — captured from a real run, not written to look plausible:
var name: String = nil print(name)
Main.swift:2:20: error: 'nil' cannot initialize specified type 'String'
var name: String = nil
^
Main.swift:2:11: note: add '?' to form the optional type 'String?'
var name: String = nil
^
?
Swift even suggests the exact fix: add ? to the type. Separately, ?? (the nil-coalescing operator) supplies a fallback value in a single expression, without needing an if let or guard let at all — a shorter alternative when all you need is a default.
Next: arrays and dictionaries — Swift's two core collection types.
Practice exercise
Write a function named describe that takes a String? and returns its value, or "unknown" if the value is nil, using the ?? operator. Call describe(nil) and print the result.