0
0
Swiftprogramming~5 mins

Ternary conditional operator in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Acondition ? valueIfTrue : valueIfFalse
Bif condition then valueIfTrue else valueIfFalse
Ccondition : valueIfTrue ? valueIfFalse
Dcondition ? valueIfFalse : valueIfTrue
What will this Swift code print? let age = 20; print(age >= 18 ? "Adult" : "Minor")
AError
BMinor
C20
DAdult
Can the ternary operator replace all if-else statements in Swift?
AOnly for loops
BYes, always
CNo, only simple conditional expressions
DOnly for functions
What happens if the true and false expressions in a ternary operator return different types?
ACompilation error
BIt will run but give wrong results
CSwift will automatically convert types
DIt will ignore the false expression
Which of these is a good use of the ternary operator?
AReplacing complex nested if-else blocks
BAssigning a value based on a simple condition
CWriting loops
DDeclaring functions
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.