Optionals: a value may be absent
Optionals: a value may be absent
A student may not yet have a recorded score. Zero is a real score and should not also mean “missing.” Swift represents possible absence with an optional type, written with a question mark. An Int? contains either an integer or nil; it is not a separate numeric sentinel convention.
What you’ll learn
- Represent an absent score with Int? and nil.
- Choose an explicit fallback rather than forcing an unwrap.
Optionals: a value may be absent in the example
Absent value nil
A student may not yet have a recorded score.
Absent value nilHandle absence
An optional must be handled before using its wrapped value as an ordinary Int.
Handle absencePresent value 80
The initial optional has no value, so the first line displays -1.
Present value 80
How optionals: a value may be absent works
An optional must be handled before using its wrapped value as an ordinary Int. ?? supplies a fallback when nil is present. Optional binding lets you work with the value only when available. Force unwrapping with ! asserts a value exists and can trap if that assertion is wrong.
Work through optionals: a value may be absent
Save this complete program as main.swift and run it with the Swift toolchain. No separate input file is needed.
Swift · complete program
var score: Int? = nil
print(score ?? -1)
score = 80
print(score ?? -1)Expected output
-1
80Follow the execution
The initial optional has no value, so the first line displays -1. After assignment it contains 80, and the second display uses 80. The negative number is only a visible fallback for this demonstration; the optional itself still distinguishes absence from an actual score.
Try this program in the Swift compiler. Paste the complete source above.
Practice: Optionals: a value may be absent
Your task: Would storing zero instead of nil preserve the distinction between missing and zero marks?
Swift · complete program
var score: Int? = nil
print(score ?? -1)
score = 80
print(score ?? -1)Worked answer
No. The application could no longer tell a genuine zero from an absent mark without another convention. Int? expresses that distinction directly and requires the program to consider absence.
Represent a missing mark honestly
Do not force unwrap merely to silence a compiler diagnostic. Choose a fallback only if it makes sense for the task; a missing mark might need an “Awaiting result” message rather than arithmetic with -1.
Check your decision
Check the practical consequence
Represent a missing mark honestly
No. The application could no longer tell a genuine zero from an absent mark without another convention. Int? expresses that distinction directly and requires the program to consider absence. Do not force unwrap merely to silence a compiler diagnostic.
Further reading: official Swift language guide.
Reaching the recap and completing the quizzes are separate milestones.