2016-09-30 17 views
6

Uczę się używać predykatów do filtrowania. Znalazłem tutorial, ale jeden aspekt nie działa na mnie w Swift 3. Oto specyficzny kod:SWIFT 3 Predykat dla NSArray nie działa poprawnie z numerami

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 kompilacji, ale ostatnie 2 produkować żadnych wyników, chociaż mam przypadek, w którym wiek = 33. Oto testowy pełny kod testowy z samouczka:

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

Co robię źle? Dzięki.

Odpowiedz

15

Dlaczego dwie ostatnie prace? Przekazujesz ciąg znaków dla właściwości Int. Musisz podać wartość Int, aby porównać z właściwością Int.

Zmiana dwa ostatnie do:

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

Uwaga zmiana specyfikacją formatu z %@ do %d.

+0

Dziękuję bardzo. Tak łatwo. Czy wiesz, gdzie mogę znaleźć to udokumentowane? – Frederic

+2

Prawdopodobnie [Podręcznik programowania predykatów] (https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/AdditionalChapters/Introduction.html#//apple_ref/doc/uid/TP40001798-SW1) – rmaddy

+0

To jest świetna odpowiedź. Czytałem dokumentację i przykłady. To oczywiste, kiedy widzę odpowiedź, ale nigdzie nie widziałem tej dokumentacji .. –

Powiązane problemy