Monday, October 9, 2017

Swift NSPredicate with Array

NSPredicate is a class that specify data format. It shows how data to be fetched. If you are familiar with SQL language, you will find it easy to use it. The example below show how it is used in normal array.

First create Person model to use with Array



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

}

Then create an array of person with some initialize data


let arrPeople = [
            Person(name: "Mary", age: 21, salary: 100),
            Person(name: "Tina", age: 22, salary: 200),
            Person(name: "Kin", age: 23, salary: 300),
            Person(name: "Pal", age: 24, salary: 400),
            Person(name: "Qusa", age: 25, salary: 500)

        ]

Create 3 predicate consisting of Name, Age and Salary


let namePredicate =  NSPredicate(format: "name == \"Qusa\" ", argumentArray: nil)
let agePredicate = NSPredicate(format: "age == 22", argumentArray: nil)
let salaryPredicate = NSPredicate(format: "salary == 300", argumentArray: nil)

Then fetch the result from the 3 predicates using function Filtered


let arrName = (arrPeople as NSArray).filtered(using: namePredicate) as! [Person]
let arrAge = (arrPeople as NSArray).filtered(using: agePredicate) as! [Person]
let arrSalary = (arrPeople as NSArray).filtered(using: salaryPredicate) as! [Person]

Finally print to see the result


print("Predicate name result : \(arrName.first?.name ?? "" ) ")
print("Predicate age result : \(arrAge.first?.name ?? "" )")
print("Predicate salary result : \(arrSalary.first?.name ?? "" )")









Congratulation, you just know how to use NSPredicate with Array. Here is the full source code.


1 comment:

  1. If you have any question regarding to this topic or any errors with my content, please give me feedbacks.

    ReplyDelete