领域:使用IN运算符过滤

net*_*000 7 realm swift

我有一个整数数组:

? 2 elements
  - [0] : 123459
  - [1] : 1031020
Run Code Online (Sandbox Code Playgroud)

并希望根据数组过滤我的对象.

.filter("code IN \(myCodeArray)")
Run Code Online (Sandbox Code Playgroud)

但这会导致崩溃.如何正确使用IN运算符?

bda*_*ash 14

不应使用Swift的字符串插值,而应使用NSPredicate's参数替换支持%@:

.filter("code IN %@", myCodeArray)
Run Code Online (Sandbox Code Playgroud)

Swift的字符串插值语法("\(someVariable)")将变量的字符串表示形式插入到字符串中.整数数组的字符串表示形式[123459, 1031020],NSPredicate格式字符串中无效.使用%@将对象替换为谓词而无需担心对象的Swift字符串表示是否与NSPredicate期望的匹配.