Bird
0
0

Given a dictionary of student scores, use a ternary operator in Swift to create a new dictionary that marks each student as "Pass" if their score is 50 or more, otherwise "Fail".

hard📝 Application Q15 of 15
Swift - Operators and Expressions
Given a dictionary of student scores, use a ternary operator in Swift to create a new dictionary that marks each student as "Pass" if their score is 50 or more, otherwise "Fail".
What is the correct way to write this using dictionary comprehension?
let scores = ["Anna": 75, "Ben": 45, "Cara": 50]
let results = scores.mapValues { score in
    // Fill in here
}
Ascore >= 50 ? "Pass" : "Fail"
Bif score >= 50 { "Pass" } else { "Fail" }
Cscore > 50 ? "Pass" : "Fail"
Dscore >= 50 ? "Fail" : "Pass"
Step-by-Step Solution
Solution:
  1. Step 1: Understand the condition for passing

    Students pass if their score is 50 or more, so condition is score >= 50.
  2. Step 2: Apply ternary operator correctly

    Use ternary to return "Pass" if true, else "Fail".
  3. Final Answer:

    score >= 50 ? "Pass" : "Fail" -> Option A
  4. Quick Check:

    Use condition ? "Pass" : "Fail" for mapping [OK]
Quick Trick: Use mapValues with ternary: condition ? trueVal : falseVal [OK]
Common Mistakes:
  • Using if-else instead of ternary in mapValues
  • Wrong comparison operator (>)
  • Swapping Pass and Fail values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes