Can I use an NSPredicate in Swift with a nil argument?

The easiest solution and fitting for you case would be to simply write the predicate as:

NSPredicate(format: "parentFolder == nil")

But if it is necessary to insert nil as an argument you could use NSNull. This might be useful if you are using an Optional

let folderName: String? = nil
// ... assign folderName if available
NSPredicate(format: "parentFolder == %@", folderName ?? NSNull())

This will result in all folder with the same parent, if the parent is nil, it will fetch all folders without parent.


It looks as if it is (with the current Xcode 6 beta 3 release) generally difficult to pass nil in a variable argument list.

This seems to work:

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")