Bird
0
0

Identify the error in this Swift code using NSPredicate and sorting:

medium📝 Debug Q14 of 15
iOS Swift - Local Data Persistence
Identify the error in this Swift code using NSPredicate and sorting:
let numbers = [5, 3, 8, 1]
let predicate = NSPredicate(format: "SELF > 4")
let filtered = numbers.filter { predicate.evaluate(with: $0) }
let sorted = filtered.sorted(by: { $0 < $1 })
print(sorted)
ANSPredicate format string is incorrect
BNo error; code works as expected
CFiltering with predicate.evaluate(with:) is correct
DCannot use NSPredicate with Int values
Step-by-Step Solution
Solution:
  1. Step 1: Check NSPredicate format

    The format "SELF > 4" is valid for filtering numbers greater than 4.
  2. Step 2: Verify filtering and sorting logic

    Using predicate.evaluate(with:) inside filter is valid; sorting ascending is correct.
  3. Final Answer:

    No error; code works as expected -> Option B
  4. Quick Check:

    Predicate with Int and filter works fine [OK]
Quick Trick: Evaluate predicate inside filter is valid for Int arrays [OK]
Common Mistakes:
  • Thinking NSPredicate can't filter Ints
  • Assuming format string is wrong
  • Expecting error in sorting syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes