What if you could find and organize any data instantly with just a simple rule?
Why Predicates and sorting in iOS Swift? - Purpose & Use Cases
Imagine you have a big list of contacts on your phone. You want to find only those who live in your city and then see them sorted by their last name.
Trying to do this by checking each contact one by one and then sorting them manually is slow and tiring. It's easy to make mistakes or miss some contacts.
Using predicates and sorting lets you quickly filter your contacts by any rule you want and then arrange them neatly, all with just a few lines of code.
var filtered = [Contact]() for contact in contacts { if contact.city == "MyCity" { filtered.append(contact) } } filtered.sort { $0.lastName < $1.lastName }
let predicate = NSPredicate(format: "city == %@", "MyCity") let filtered = (contacts as NSArray).filtered(using: predicate) as! [Contact] let sorted = filtered.sorted { $0.lastName < $1.lastName }
You can quickly find and organize any data you want, making your app smarter and faster.
When you search for songs in your music app by genre and then sort them by artist name, predicates and sorting do the heavy lifting behind the scenes.
Manual filtering and sorting is slow and error-prone.
Predicates let you filter data easily with clear rules.
Sorting organizes your filtered data quickly and cleanly.
Practice
NSPredicate do in Swift when working with arrays?Solution
Step 1: Understand the role of NSPredicate
An NSPredicate is used to specify conditions to filter collections like arrays.Step 2: Differentiate filtering from sorting
Filtering means selecting items that meet a condition, while sorting changes order.Final Answer:
Filters the array to include only items matching a condition -> Option DQuick Check:
Predicate = Filter [OK]
- Confusing predicate with sorting
- Thinking predicate adds or removes items
- Assuming predicate changes order
Solution
Step 1: Recall NSPredicate format syntax
NSPredicate uses format strings with == for equality comparison.Step 2: Identify correct equality operator
== is the correct operator; = or === are invalid in NSPredicate format.Final Answer:
NSPredicate(format: "name == 'John'") -> Option AQuick Check:
Use == for equality in NSPredicate [OK]
- Using single equals (=) instead of double (==)
- Using === which is not valid in NSPredicate
- Writing 'equals' as a word instead of operator
let names = ["Anna", "John", "Bob", "Alice"]
let predicate = NSPredicate(format: "SELF BEGINSWITH[c] 'A'")
let filtered = (names as NSArray).filtered(using: predicate) as! [String]
let sorted = filtered.sorted(by: { $0 > $1 })
print(sorted)Solution
Step 1: Filter names starting with 'A' ignoring case
The predicate selects names beginning with 'A' or 'a': "Anna" and "Alice".Step 2: Sort filtered names descending
Sorting with $0 > $1 means descending order alphabetically: "Alice" comes before "Anna".Final Answer:
["Alice", "Anna"] -> Option AQuick Check:
Filter by 'A', then descending sort = ["Alice", "Anna"] [OK]
- Sorting ascending instead of descending
- Ignoring case sensitivity in predicate
- Confusing filter and sort order
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)Solution
Step 1: Check NSPredicate format
The format "SELF > 4" is valid for filtering numbers greater than 4.Step 2: Verify filtering and sorting logic
Using predicate.evaluate(with:) inside filter is valid; sorting ascending is correct.Final Answer:
No error; code works as expected -> Option BQuick Check:
Predicate with Int and filter works fine [OK]
- Thinking NSPredicate can't filter Ints
- Assuming format string is wrong
- Expecting error in sorting syntax
let people = [ ["name": "John", "age": 30], ["name": "Alice", "age": 25], ["name": "Bob", "age": 30], ["name": "Carol", "age": 25] ]How do you filter for people aged 25 and sort them by name ascending using NSPredicate and Swift sorting?
Solution
Step 1: Write correct NSPredicate for age 25
Use "age == 25" to filter exactly age 25; single equals is invalid.Step 2: Sort filtered array by name ascending
Sort by comparing names with < operator for ascending order.Final Answer:
Use NSPredicate(format: "age == 25") and sort with sorted(by: { $0["name"]! < $1["name"]! }) -> Option CQuick Check:
Filter age == 25, sort by name ascending [OK]
- Using single = instead of ==
- Comparing age as string '25' instead of number
- Sorting by age instead of name
Ready to prove it?
Pass the test and this pattern moves unknown
