0
0
Swiftprogramming~10 mins

Ternary conditional operator in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Ternary conditional operator
Evaluate condition
Yes
Use value if true
End
No
Use value if false
End
The ternary operator checks a condition and chooses one of two values based on true or false.
Execution Sample
Swift
let age = 20
let canVote = age >= 18 ? "Yes" : "No"
print(canVote)
This code checks if age is 18 or more and sets canVote to "Yes" or "No" accordingly.
Execution Table
StepCondition (age >= 18)ResultValue chosenOutput
120 >= 18true"Yes"canVote = "Yes"
2End--Prints: Yes
💡 Condition true, so "Yes" chosen and printed.
Variable Tracker
VariableStartAfter Step 1Final
age202020
canVoteundefined"Yes""Yes"
Key Moments - 2 Insights
Why does canVote get "Yes" and not "No"?
Because the condition age >= 18 is true at step 1 in the execution table, so the true value "Yes" is chosen.
What if age was 16? What value would canVote get?
If age was 16, the condition would be false, so the false value "No" would be chosen instead, as shown by the ternary operator logic in the concept flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of canVote after step 1?
A"No"
B"Yes"
Cundefined
D20
💡 Hint
Check the 'Value chosen' and 'Output' columns in row 1 of the execution table.
At which step does the program print the output?
AStep 2
BBefore step 1
CStep 1
DNo output printed
💡 Hint
Look at the 'Output' column in the execution table rows.
If age was 17, what would the ternary operator choose?
A"Yes"
Bundefined
C"No"
DError
💡 Hint
Refer to the concept flow and key moments about condition false choice.
Concept Snapshot
Ternary conditional operator syntax:
condition ? valueIfTrue : valueIfFalse
It evaluates the condition once.
If true, returns valueIfTrue.
If false, returns valueIfFalse.
Used for simple if-else in one line.
Full Transcript
The ternary conditional operator in Swift lets you pick one of two values based on a condition. First, the condition is checked. If it is true, the value after the question mark is chosen. If false, the value after the colon is chosen. For example, if age is 20, the condition age >= 18 is true, so canVote becomes "Yes". Then the program prints "Yes". If age was less than 18, canVote would be "No". This operator is a shortcut for simple if-else statements and helps write cleaner code.