NSPredicate的不一致

Jay*_*ayo 0 nspredicate ios swift

我想知道为什么这个NSPredicate有效:

let companyPredicate = NSPredicate(format: "company = '1'")
Run Code Online (Sandbox Code Playgroud)

但不是这个:

let companyPredicate = NSPredicate(format: "company = '%@'", 1)
Run Code Online (Sandbox Code Playgroud)

而且这个:

let companyPredicate = NSPredicate(format: "company = '%@'", company)
Run Code Online (Sandbox Code Playgroud)

当我打印公司的价值.输出为Optional(1).

那么为什么第一行代码有效呢?

Mar*_*n R 5

来自"谓词编程指南"中的谓词格式字符串语法:

单引号或双引号变量...导致%@,%K或$变量被解释为格式字符串中的文字,因此阻止任何替换.

所以在你的第二个谓词中,你将"company"属性与文字字符串进行比较"%@":

let p1 = NSPredicate(format: "company = '%@'", 1)
print(p1) // company == "%@"
Run Code Online (Sandbox Code Playgroud)

要与整数进行比较,请使用

let p2 = NSPredicate(format: "company = %@", NSNumber(integer: 1))
print(p2) // company == 1
Run Code Online (Sandbox Code Playgroud)

要么

let p3 = NSPredicate(format: "company = %ld", 1)
Run Code Online (Sandbox Code Playgroud)