Skip to content

Instantly share code, notes, and snippets.

@sisoje
Last active February 7, 2019 11:56
Show Gist options
  • Save sisoje/7a844e230ee775fae754e3df4527e5c8 to your computer and use it in GitHub Desktop.
Save sisoje/7a844e230ee775fae754e3df4527e5c8 to your computer and use it in GitHub Desktop.
struct Person {
let name: String
let age: Int
}
let persons = [
Person(name: "Pera", age: 20),
Person(name: "Mika", age: 30),
Person(name: "Laza", age: 40)
]
// valid predicates
let namePredicate = NSPredicate(format: "name = %@", "Mika")
let agePredicate = NSPredicate(format: "age >= %@", 30)
let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [namePredicate, agePredicate])
// compiles but fails in runtime - wrong type
let wrongPredicate1 = NSPredicate(format: "age >= %@", "text")
// compiles but fails in runtime - wrong property
let wrongPredicate2 = NSPredicate(format: "password == %@", "123")
// finds two: (Mika, 30) and (Laza, 40)
_ = persons.filtered(using: agePredicate)
// finds one: (Mika, 30)
_ = persons.filtered(using: compoundPredicate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment