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

后端 未结 2 855
再見小時候
再見小時候 2020-12-20 11:13

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 fo

2条回答
  •  情深已故
    2020-12-20 11:51

    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.

提交回复
热议问题