Challenge - 5 Problems
Ternary Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple ternary expression
What is the output of this Swift code?
Swift
let a = 10 let b = 20 let result = a > b ? "a is greater" : "b is greater" print(result)
Attempts:
2 left
💡 Hint
Compare the values of a and b carefully.
✗ Incorrect
Since 10 is not greater than 20, the condition is false, so the else part "b is greater" is chosen.
❓ Predict Output
intermediate2:00remaining
Ternary operator with numeric result
What will be printed by this Swift code?
Swift
let x = 5 let y = 8 let max = x > y ? x : y print(max)
Attempts:
2 left
💡 Hint
Check which number is bigger.
✗ Incorrect
Since 5 is not greater than 8, the else part y (8) is assigned to max.
❓ Predict Output
advanced2:30remaining
Nested ternary conditional output
What is the output of this Swift code?
Swift
let score = 75 let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F" print(grade)
Attempts:
2 left
💡 Hint
Evaluate conditions from left to right.
✗ Incorrect
75 is not >= 90 or 80, but it is >= 70, so grade is "C".
❓ Predict Output
advanced2:00remaining
Ternary operator with Boolean result
What does this Swift code print?
Swift
let isSunny = false let activity = isSunny ? "Go outside" : "Stay inside" print(activity)
Attempts:
2 left
💡 Hint
Check the Boolean value of isSunny.
✗ Incorrect
Since isSunny is false, the else part "Stay inside" is chosen.
❓ Predict Output
expert3:00remaining
Complex ternary with side effects
What is the output of this Swift code?
Swift
var count = 0 let result = count == 0 ? "Zero" : { count += 1; return "Not zero" }() print(result) print(count)
Attempts:
2 left
💡 Hint
Notice when the closure is executed.
✗ Incorrect
Since count == 0 is true, the first string "Zero" is assigned and the closure is not executed, so count stays 0.