Using Predicate in Swift Using Predicate in Swift swift swift

Using Predicate in Swift


This is really just a syntax switch. OK, so we have this method call:

[NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];

In Swift, constructors skip the "blahWith…" part and just use the class name as a function and then go straight to the arguments, so [NSPredicate predicateWithFormat: …] would become NSPredicate(format: …). (For another example, [NSArray arrayWithObject: …] would become NSArray(object: …). This is a regular pattern in Swift.)

So now we just need to pass the arguments to the constructor. In Objective-C, NSString literals look like @"", but in Swift we just use quotation marks for strings. So that gives us:

let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)

And in fact that is exactly what we need here.

(Incidentally, you'll notice some of the other answers instead use a format string like "name contains[c] \(searchText)". That is not correct. That uses string interpolation, which is different from predicate formatting and will generally not work for this.)


Working with predicate for pretty long time. Here is my conclusion (SWIFT)

//Customizable! (for me was just important if at least one)request.fetchLimit = 1//IF IS EQUAL//1 OBJECTrequest.predicate = NSPredicate(format: "name = %@", txtFieldName.text)//ARRAYrequest.predicate = NSPredicate(format: "name = %@ AND nickName = %@", argumentArray: [name, nickname])// IF CONTAINS//1 OBJECTrequest.predicate = NSPredicate(format: "name contains[c] %@", txtFieldName.text)//ARRAYrequest.predicate = NSPredicate(format: "name contains[c] %@ AND nickName contains[c] %@", argumentArray: [name, nickname])


Example how to use in swift 2.0

let dataSource = [    "Domain CheckService",    "IMEI check",    "Compliant about service provider",    "Compliant about TRA",    "Enquires",    "Suggestion",    "SMS Spam",    "Poor Coverage",    "Help Salim"]let searchString = "Enq"let predicate = NSPredicate(format: "SELF contains %@", searchString)let searchDataSource = dataSource.filter { predicate.evaluateWithObject($0) }

You will get (playground)

enter image description here