Bird
0
0

Given a dictionary let items = ["pen": 3, "notebook": 0, "eraser": 2], which Swift code correctly creates a new dictionary containing only items with quantity greater than zero?

hard📝 Application Q15 of 15
Swift - Collections
Given a dictionary let items = ["pen": 3, "notebook": 0, "eraser": 2], which Swift code correctly creates a new dictionary containing only items with quantity greater than zero?
Alet filtered = items.compactMap { $0.value > 0 }
Blet filtered = items.filter { $0.key > 0 }
Clet filtered = items.filter { $0.value > 0 }
Dlet filtered = items.map { $0.value > 0 }
Step-by-Step Solution
Solution:
  1. Step 1: Understand filtering dictionary by value

    We want to keep pairs where value > 0, so filter with condition on $0.value.
  2. Step 2: Analyze each option

    let filtered = items.filter { $0.value > 0 } uses filter with correct condition. let filtered = items.filter { $0.key > 0 } incorrectly compares key (a String) to 0. Options A and C use map/compactMap which transform values, not filter pairs.
  3. Final Answer:

    let filtered = items.filter { $0.value > 0 } -> Option C
  4. Quick Check:

    Filter dictionary by value > 0 = let filtered = items.filter { $0.value > 0 } [OK]
Quick Trick: Use filter with $0.value condition to keep matching pairs [OK]
Common Mistakes:
  • Filtering by key instead of value
  • Using map instead of filter for selection
  • Using compactMap which changes type, not filters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes