Tôi đang học cách sử dụng các biến vị ngữ để lọc. Tôi tìm thấy một hướng dẫn, nhưng một khía cạnh không được làm việc cho tôi trong Swift 3. Dưới đây là một số mã cụ thể:SWIFT 3 Dành cho NSArray không hoạt động đúng với số
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
Tất cả 4 biên dịch, nhưng cuối cùng 2 sản xuất không có kết quả mặc dù tôi có một trường hợp tuổi = 33. Đây là mã kiểm tra hoàn thành thử nghiệm từ hướng dẫn:
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)
// []
Tôi đang làm gì sai? Cảm ơn.
Cảm ơn rất nhiều. Quá dễ. Bạn có biết nơi tôi có thể tìm thấy tài liệu này? – Frederic
Có lẽ là [Hướng dẫn lập trình dành riêng] (https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/AdditionalChapters/Introduction.html#//apple_ref/doc/uid/TP40001798-SW1) – rmaddy
Đây là một câu trả lời tuyệt vời. Tôi đã đọc tài liệu và ví dụ. Rõ ràng khi tôi nhìn thấy câu trả lời, nhưng tôi đã không thấy tài liệu này ở bất cứ đâu .. –