Starter lesson
Handle optional input safely
An optional communicates that a value may be absent. Unwrap it deliberately and define a useful fallback instead of force-unwrapping.
import Foundation
func displayName(_ value: String?) -> String {
guard let name = value?.trimmingCharacters(in: .whitespacesAndNewlines),
!name.isEmpty else {
return "Guest"
}
return name
}
print(displayName(" Asha "))
print(displayName(nil))
What to expect
Asha
Guest
Key idea: Model missing data explicitly and keep fallback behavior close to the place that needs it.