2016-09-30 55 views
6

我正在学习使用谓词进行过滤。我发现了一个教程,而是一个方面是不是在斯威夫特3.工作对我来说这是一些特定的代码:SWIFT 3谓词NSArray无法正常使用数字

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

我在做什么错了?谢谢。

回答

15

为什么最后两个工作?你传递一个字符串作为Int属性。您需要通过Int才能与Int房产进行比较。

改变过去两年来:

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

注意格式说明从%@%d的变化。

+0

非常感谢。太简单。你知道我在哪里可以找到这个记录? – Frederic

+2

可能是[Predicate Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/AdditionalChapters/Introduction.html#//apple_ref/doc/uid/TP40001798-SW1) – rmaddy

+0

这是一个很好的答案。我已阅读文档和示例。当我看到答案时,很明显,但我没有看到这个文档记录在任何地方.. –