2016-09-30 11 views
6

के साथ ठीक से काम नहीं कर रहा है मैं फ़िल्टरिंग के लिए भविष्यवाणियों का उपयोग करना सीख रहा हूं। मैं एक ट्यूटोरियल पाया है, लेकिन एक पहलू स्विफ्ट 3. में मेरे लिए काम नहीं कर रहा है यहाँ कुछ विशिष्ट कोड है:स्विफ्ट 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 कोई परिणाम भले ही मैं एक मामला है जहां उम्र =

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

क्या मैं गलत कर रहा हूँ: 33. यहाँ ट्यूटोरियल से परीक्षण पूरा परीक्षण कोड है? धन्यवाद।

उत्तर

15

पिछले दो काम क्यों करेंगे? आप Int संपत्ति के लिए एक स्ट्रिंग पास कर रहे हैं। Int संपत्ति के विरुद्ध तुलना करने के लिए आपको Int में प्रवेश करने की आवश्यकता है।

बदलें पिछले दो के लिए:

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

यह एक अच्छा जवाब है। मैंने दस्तावेज़ीकरण और उदाहरण पढ़े हैं। यह स्पष्ट है जब मैं जवाब देखता हूं, लेकिन मैंने इसे कहीं भी दस्तावेज नहीं देखा है .. –