如何过滤 NSPredicate 以包含在 Swift 中?

How to filter NSPredicate for inclusion in Swift?

我需要使用 IN 进行过滤。这是我的代码:

let choices = "1,2,3,4"

然后像这样使用它,这会导致应用程序崩溃:

NSPredicate(format: "id in %@", @choices)

我也试过:

NSPredicate(format: "id in [1,2,3,4]")

但是得到这个错误:

'Unable to parse the format string "id in [1,2,3,4]"'

let choices = "1,2,3,4" - 是字符串,必须是数组 let choices = [1,2,3,4]

如果 id 是您要比较的 属性 -

NSPredicate(format: "id in %@", @choices)@choices 替换为 choices

结果 - NSPredicate(format: "id in %@", choices)

如果要比较对象本身 NSPredicate(format: "self in %@", @choices)@choices 替换为 choices,并将 id 替换为 self

结果 - NSPredicate(format: "self in %@", choices) self 是(指向)给定谓词 compared/evaluated 的对象。

选项需要用大括号 {} 括起来。然后就可以了

NSPredicate(format: "id in {\(choices)}")

生成的字符串如下所示:

id in {1,2,3,4}