Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 域筛选器未将Int64作为参数_Swift_Realm - Fatal编程技术网

Swift 域筛选器未将Int64作为参数

Swift 域筛选器未将Int64作为参数,swift,realm,Swift,Realm,我有一个ID为Int64的对象: 应用程序崩溃,出现以下错误: 'Invalid value', reason: 'Expected object of type int for property 'id' on object of type 'MyObject', but received: Optional(2)' 当我这样做时: let object = myObjectsList.filter("id = \(myObject.id.value)").first; // crash

我有一个ID为Int64的对象:

应用程序崩溃,出现以下错误:

'Invalid value', reason: 'Expected object of type int for property 'id' on object of type 'MyObject', but received: Optional(2)'
当我这样做时:

let object = myObjectsList.filter("id = \(myObject.id.value)").first; // crash
错误是:

'NSInvalidArgumentException', reason: 'unable to parse function name 'Optional:' into supported selector (Optional:)'
'NSInvalidArgumentException', reason: 'unable to parse the format string "id = RealmSwift.RealmOptional<Swift.Int64>"'
当我这样做的时候:

let object = myObjectsList.filter("id = \(myObject.id)").first; // crash
错误是:

'NSInvalidArgumentException', reason: 'unable to parse function name 'Optional:' into supported selector (Optional:)'
'NSInvalidArgumentException', reason: 'unable to parse the format string "id = RealmSwift.RealmOptional<Swift.Int64>"'
那么,我应该如何使用对象id过滤对象呢?

您想要:

let object = myObjectsList.filter("id = %@", objectID ?? NSNull()).first
值得强调的是,Swift的\someVariable字符串插值和NSPredicate的%@参数替换语法不能互换。前者将变量的字符串表示形式插入到谓词字符串中,然后由NSPredicate进行解析。使用%@将对对象的引用替换为生成的NSPredicate对象。这种差异解释了为什么在两次尝试中解析谓词格式字符串时会出现错误


需要注意的第二件事是,由于查询是由NSPredicate(一种Objective-C类型)表示的,因此被替换的参数需要遵循其约定。特别是,Swift期权不能用于表示存在或不存在价值,因为Objective-C不知道期权。相反,非可选类型可以表示存在值,而NSNull实例表示没有值。在上面的代码中,我使用了???,Swift的nil合并运算符来实现此映射。

Hi。谢谢您的回答,但这也不起作用:原因:'对于'MyObject'类型的对象,属性'id'预期的对象为int类型,但收到的是:2'但起作用的是:filterid=\objectID!如Int64;