Bird
0
0

You want to assign a string describing a number's sign using the ternary operator. Which code correctly assigns "Positive", "Negative", or "Zero" to the variable sign?

hard📝 Application Q8 of 15
Swift - Operators and Expressions
You want to assign a string describing a number's sign using the ternary operator. Which code correctly assigns "Positive", "Negative", or "Zero" to the variable sign?
Alet sign = number > 0 ? "Positive" : number == 0 ? "Negative" : "Zero"
Blet sign = number > 0 ? "Positive" : number < 0 ? "Negative" : "Zero"
Clet sign = number > 0 ? "Positive" : "Negative" : "Zero"
Dlet sign = number > 0 ? "Positive" : number < 0 ? "Zero" : "Negative"
Step-by-Step Solution
Solution:
  1. Step 1: Understand the logic for sign assignment

    We want "Positive" if number > 0, "Negative" if number < 0, and "Zero" otherwise.
  2. Step 2: Check each option's logic

    let sign = number > 0 ? "Positive" : number < 0 ? "Negative" : "Zero" correctly nests ternary operators to check number > 0, then number < 0, else "Zero". let sign = number > 0 ? "Positive" : number < 0 ? "Zero" : "Negative" swaps "Zero" and "Negative" incorrectly. let sign = number > 0 ? "Positive" : "Negative" : "Zero" has invalid syntax with two colons. let sign = number > 0 ? "Positive" : number == 0 ? "Negative" : "Zero" swaps "Zero" and "Negative" incorrectly.
  3. Final Answer:

    let sign = number > 0 ? "Positive" : number < 0 ? "Negative" : "Zero" -> Option B
  4. Quick Check:

    Nested ternary matches sign logic [OK]
Quick Trick: Nest ternary operators carefully for multiple conditions [OK]
Common Mistakes:
  • Swapping order of conditions
  • Incorrect colon placement
  • Using invalid syntax with multiple colons

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes