Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIFT 3 Predicate for NSArray not working properly with numbers

I am learning to use predicates for filtering. I found a tutorial, but one aspect is not working for me in Swift 3. Here is some specific code:

let ageIs33Predicate01 = NSPredicate(format: "age = 33") //THIS WORKS
let ageIs33Predicate02 = NSPredicate(format: "%K = 33", "age") //THIS WORKS
let ageIs33Predicate03 = NSPredicate(format: "%K = %@", "age","33") //THIS DOESN'T WORK
let ageIs33Predicate04 = NSPredicate(format: "age = %@","33") //THIS DOESN'T WORK

All 4 compile, but the last 2 produce no results even though I have a case where age = 33. Here is the test complete test code from the tutorial:

import Foundation

class Person: NSObject {
    let firstName: String
    let lastName: String
    let age: Int

    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }

    override var description: String {
        return "\(firstName) \(lastName)"
    }
}

let alice = Person(firstName: "Alice", lastName: "Smith", age: 24)
let bob = Person(firstName: "Bob", lastName: "Jones", age: 27)
let charlie = Person(firstName: "Charlie", lastName: "Smith", age: 33)
let quentin = Person(firstName: "Quentin", lastName: "Alberts", age: 31)
let people = [alice, bob, charlie, quentin]

let ageIs33Predicate01 = NSPredicate(format: "age = 33")
let ageIs33Predicate02 = NSPredicate(format: "%K = 33", "age")
let ageIs33Predicate03 = NSPredicate(format: "%K = %@", "age","33")
let ageIs33Predicate04 = NSPredicate(format: "age = %@","33")

(people as NSArray).filtered(using: ageIs33Predicate01)
// ["Charlie Smith"]

(people as NSArray).filtered(using: ageIs33Predicate02)
// ["Charlie Smith"]

(people as NSArray).filtered(using: ageIs33Predicate03)
// []

(people as NSArray).filtered(using: ageIs33Predicate04)
// []

What am I doing wrong? Thanks.

like image 563
Frederic Avatar asked Sep 30 '16 03:09

Frederic


1 Answers

Why would the last two work? You are passing a String in for an Int property. You need to pass in an Int to compare against the Int property.

Change the last two to:

let ageIs33Predicate03 = NSPredicate(format: "%K = %d", "age", 33)
let ageIs33Predicate04 = NSPredicate(format: "age = %d", 33)

Note the change in the format specifier from %@ to %d.

like image 68
rmaddy Avatar answered Nov 03 '22 09:11

rmaddy