gpt4 book ai didi

nsarray - 用于NSArray的SWIFT 3谓词不能与数字一起正常使用

转载 作者:行者123 更新时间:2023-12-04 04:54:38 26 4
gpt4 key购买 nike

我正在学习使用谓词进行过滤。我找到了一个教程,但是其中一个方面在Swift 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个都编译,但是即使我有age = 33的情况,最后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)
// []

我究竟做错了什么?谢谢。

最佳答案

为什么最后两个会起作用?您正在为Int属性传递一个字符串。您需要传递一个IntInt属性进行比较。

将最后两个更改为:

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

请注意,格式说明符从 %@更改为 %d

关于nsarray - 用于NSArray的SWIFT 3谓词不能与数字一起正常使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39783124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com