27

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.

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];

In converting to Swift, I'd like to do the same thing:

let request = NSFetchRequest(entityName: "Folder")
request.predicate = NSPredicate(format: "parentFolder == %@", nil)

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

Is there a correct way to do this in Swift?

Jim Rhoades
  • 3,310
  • 3
  • 34
  • 50

2 Answers2

51

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")
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Should it be "parentFolder == nil" or "parentFolder = nil"? I mean "==" vs. "=" – Roman Mar 28 '22 at 06:56
  • 1
    @Roman: It makes no difference. You can use both `==` and `=` in a predicate format string, compare https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-215832 – Martin R Mar 28 '22 at 08:10
8

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.

simonnickel
  • 548
  • 6
  • 12