2016-09-30 5 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

なぜ最後の2つは機能しますか? IntプロパティのStringを渡しています。 Intプロパティと比較するには、Intを渡す必要があります。

変更への最後の2:

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

%@から%dに書式指定子の変化。

+0

ありがとうございました。とても簡単。私はこれがどこに書かれているのか知っていますか? – Frederic

+2

おそらく[述語プログラミングガイド](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/AdditionalChapters/Introduction.html#//apple_ref/doc/uid/TP40001798-SW1) – rmaddy

+0

これは素晴らしい答えです。私はドキュメンテーションと例を読んだ。答えを見ると明らかですが、これはどこにも書かれていません。 –

関連する問題