2016-09-30 1 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 곳 연령 = 내가 잘못 뭐하는 거지

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

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

+0

이것은 훌륭한 대답입니다. 설명서와 예제를 읽었습니다. 그 대답을 볼 때 분명하지만, 어디서나이 문서를 보지 못했습니다 .. –

관련 문제