0
0
iOS Swiftmobile~3 mins

Why Predicates and sorting in iOS Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could find and organize any data instantly with just a simple rule?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
var filtered = [Contact]()
for contact in contacts {
  if contact.city == "MyCity" {
    filtered.append(contact)
  }
}
filtered.sort { $0.lastName < $1.lastName }
After
let predicate = NSPredicate(format: "city == %@", "MyCity")
let filtered = (contacts as NSArray).filtered(using: predicate) as! [Contact]
let sorted = filtered.sorted { $0.lastName < $1.lastName }
What It Enables

You can quickly find and organize any data you want, making your app smarter and faster.

Real Life Example

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.

Key Takeaways

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.