Reputation: 4903
I want to filter a list of realm results if the id
is nil or empty.
Here is a demo list of results :
{
"id":"1"
"name": "first"
},
{
"id":"2"
"name": "second"
},
{
"id":"3"
"name": "third"
},
{
"id":"" //here it can be empty
"name": ""
},
{
"id": nil // here it can be nil
"name": nil
}
I try to filter using the id like this but it crash :
lazy var declarations: Results<Declaration> = {
let realm = try! Realm()
return self.realm.objects(Declaration.self).filter("id == " "")
}()
Here is the model :
import RealmSwift
public final class Declaration: Object {
dynamic var id: String = ""
dynamic var name: String = ""
override public static func primaryKey() -> String? {
return "id"
}
}
Upvotes: 1
Views: 6662
Reputation: 15991
.filter("id == " "")
would definitely crash because you haven't escaped those quotes. It could need .filter("id == \"\"")
, but just using single quotes would be better.
Since Realm queries conform to NSPredicate
, copying the answer from this question, if you want to simply check if a Realm property isn't empty or nil, you should just be able to query using
lazy var declarations: Results<Declaration> = {
let realm = try! Realm()
return self.realm.objects(Declaration.self).filter("id != nil AND id != ''")
}()
Upvotes: 3