Recall & Review
beginner
What is the ternary conditional operator in Swift?
It is a shorthand way to write an if-else statement using the syntax: condition ? valueIfTrue : valueIfFalse.
Click to reveal answer
beginner
How does the ternary operator improve code readability?
It makes simple conditional assignments or expressions shorter and easier to read by reducing multiple lines into one line.
Click to reveal answer
beginner
Write a Swift example using the ternary operator to assign 'adult' or 'minor' based on age.
let status = age >= 18 ? "adult" : "minor"Click to reveal answer
intermediate
Can the ternary operator be nested in Swift? If yes, what should you be careful about?
Yes, it can be nested but it can make code hard to read and understand. Use parentheses and keep nesting minimal.
Click to reveal answer
intermediate
What types of expressions can be used with the ternary conditional operator in Swift?
Any expressions that return a value can be used, as long as the true and false parts return the same type or compatible types.
Click to reveal answer
What is the correct syntax of the ternary conditional operator in Swift?
✗ Incorrect
The ternary operator uses the syntax: condition ? valueIfTrue : valueIfFalse.
What will this Swift code print? let age = 20; print(age >= 18 ? "Adult" : "Minor")
✗ Incorrect
Since age is 20 which is >= 18, the condition is true, so it prints "Adult".
Can the ternary operator replace all if-else statements in Swift?
✗ Incorrect
The ternary operator is best for simple conditions; complex logic is clearer with if-else.
What happens if the true and false expressions in a ternary operator return different types?
✗ Incorrect
Swift requires both expressions to have compatible types; otherwise, it causes a compile error.
Which of these is a good use of the ternary operator?
✗ Incorrect
Ternary operator is ideal for simple conditional assignments, not complex logic.
Explain how the ternary conditional operator works in Swift and give a simple example.
Think of it as a short if-else that picks one of two values.
You got /5 concepts.
Describe when you should use the ternary operator and when to avoid it in Swift programming.
Consider how easy it is to read your code.
You got /4 concepts.