我可以在带有 nil 参数的 Swift 中使用 NSPredicate 吗? [英] Can I use an NSPredicate in Swift with a nil argument?
问题描述
我正在尝试将使用 Core Data 的项目从 Objective-C 转换为 Swift.
I'm trying to convert a project that uses Core Data from Objective-C to Swift.
数据模型的结构使我有一个包含其他文件夹的主文件夹 - 这些文件夹也可以通过父文件夹"关系包含其他文件夹.
The data model is structured so that I have one master folder which contains other folders - and those folders can also contain other folders, via a "parentFolder" relationship.
目前,我在 Objective-C 中执行此操作以检索主文件夹(它找到唯一没有parentFolder"的文件夹,并按预期工作):
Currently, I do this in Objective-C to retrieve the master folder (it finds the only folder without a "parentFolder", and works as expected):
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:"Folder"];
request.predicate = [NSPredicate predicateWithFormat:@"parentFolder == %@", nil];
在转换为 Swift 时,我想做同样的事情:
In converting to Swift, I'd like to do the same thing:
let request = NSFetchRequest(entityName: "Folder")
request.predicate = NSPredicate(format: "parentFolder == %@", nil)
...但编译器抱怨在调用中缺少参数标签'argumentArray:'.(我似乎混淆了它认为我需要使用 NSPredicate(format: argumentArray:) 方法代替...)
... but the compiler complains with "Missing argument label 'argumentArray:' in call. (I seem to be confusing it into thinking I need to use the NSPredicate(format: argumentArray:) method instead...)
在 Swift 中是否有正确的方法来做到这一点?
Is there a correct way to do this in Swift?
推荐答案
看起来好像(使用当前的 Xcode 6 beta 3 版本)一般很难在变量参数列表中传递 nil
.
It looks as if it is (with the current Xcode 6 beta 3 release) generally difficult
to pass nil
in a variable argument list.
这似乎有效:
let predicate = NSPredicate(format: "parentFolder == %@", 0)
print(predicate)
// Output: parentFolder == nil
但是最简单的解决方案是简单地将谓词写为
But the easiest solution would be to simply write the predicate as
NSPredicate(format: "parentFolder == nil")
这篇关于我可以在带有 nil 参数的 Swift 中使用 NSPredicate 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!