0
0
iOS Swiftmobile~5 mins

Predicates and sorting in iOS Swift

Choose your learning style9 modes available
Introduction

Predicates help you find specific items in a list. Sorting arranges items in order, like alphabetically or by number.

You want to show only contacts whose names start with 'A'.
You need to list tasks sorted by their due date.
Filtering a list of products to show only those under $20.
Sorting messages by newest first.
Finding all photos taken in a certain year.
Syntax
iOS Swift
let predicate = NSPredicate(format: "propertyName CONTAINS[c] %@", "value")
let sortedArray = array.sorted { $0.property < $1.property }

NSPredicate uses a format string to describe the filter condition.

Sorting uses the sorted method with a closure to compare items.

Examples
This finds items where the name starts with 'J', ignoring case.
iOS Swift
let predicate = NSPredicate(format: "name BEGINSWITH[c] %@", "J")
This finds items where the age is 18 or older.
iOS Swift
let predicate = NSPredicate(format: "age >= %d", 18)
This sorts people by age from youngest to oldest.
iOS Swift
let sortedArray = people.sorted { $0.age < $1.age }
This sorts people by name alphabetically, ignoring case.
iOS Swift
let sortedArray = people.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
Sample App

This program filters a list of people to only those whose names start with 'a' or 'A'. Then it sorts them by age from youngest to oldest. Finally, it prints their names and ages.

iOS Swift
import UIKit

class Person: NSObject {
  let name: String
  let age: Int
  init(name: String, age: Int) {
    self.name = name
    self.age = age
    super.init()
  }
}

let people = [
  Person(name: "Alice", age: 30),
  Person(name: "Bob", age: 20),
  Person(name: "Charlie", age: 25),
  Person(name: "anna", age: 22)
]

// Filter people whose name starts with 'A' or 'a'
let predicate = NSPredicate(format: "name BEGINSWITH[c] %@", "A")
let filteredPeople = people.filter { predicate.evaluate(with: $0) }

// Sort filtered people by age ascending
let sortedPeople = filteredPeople.sorted { $0.age < $1.age }

for person in sortedPeople {
  print("\(person.name) - \(person.age)")
}
OutputSuccess
Important Notes

NSPredicate is powerful for filtering arrays or Core Data fetch requests.

Sorting closures return true if the first item should come before the second.

Use [c] in predicates to ignore case when matching strings.

Summary

Predicates filter lists by conditions you set.

Sorting arranges items in order using a comparison.

Combine filtering and sorting to show exactly what you want in the right order.