SWIFT 3谓词NSArray无法正常使用数字

时间:2016-09-30 03:18:33

标签: nsarray nspredicate swift3

我正在学习使用谓词进行过滤。我找到了一个教程,但是在Swift 3中有一个方面对我不起作用。这是一些特定的代码:

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

所有4编译,但最后2个没有产生结果,即使我有一个年龄= 33的情况。这是教程中的测试完整测试代码:

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)
// []

我做错了什么?感谢。

1 个答案:

答案 0 :(得分:14)

为什么最后两个会起作用?您正在为Int属性传递一个String。您需要传入Int以与Int属性进行比较。

将最后两个更改为:

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

请注意格式说明符从%@%d的更改。