如何筛选NSPredicate以包含在Swift中?

如何筛选NSPredicate以包含在Swift中?,swift,nspredicate,Swift,Nspredicate,我需要使用中的进行筛选。这是我的密码: 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"
然后像这样使用,会使应用程序崩溃:

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(格式:“id in%@”,@choices)
@choices
替换为
choices

结果-
NSPredicate(格式:“id in%@”,选项)

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

结果-
NSPredicate(格式:“self in%@”,选项)

self是(指向)为给定谓词比较/计算的对象。

选择需要用大括号括起来
{
}
。那就行了

NSPredicate(format: "id in {\(choices)}")
生成的字符串如下所示:

id in {1,2,3,4}

“1,2,3,4”
真的吗<代码>@选项
?真正地真的吗?如果您真的必须将列表存储为逗号分隔的字符串,那么这可能会有所帮助:。这在CoreData中使用。id是此实体上的一个属性。虽然上述方法可能有效,但它不必是数组。这很好:NSPredicate(格式:“id in{(选项)}”)。@4thSpace需要在第一个括号前加一个\以转义它并将其识别为变量:
NSPredicate(格式:“id in{(选项)}”)
,如果
选项
包含任何特殊字符(如引号),那么它将崩溃。格式字符串中的字符串插值是一个坏主意。它是受控的,因此不会出现任何其他格式。