Search code examples
iosswiftdatabasexcoderealm

Swift Realm - "Value of type 'Results' has no member"


I am trying to get the data from a RealmDB and filter by id. As the Realm Documentation suggests (https://realm.io/docs/swift/latest/#queries) I am using:

    let realm = try! Realm()
    let Result = realm.objects(DBName.self).filter("ID == %@", id) 

XCode doesn't show any warning or errors in these two lines, but when a try to use the results by doing this:

    print(Result.ID)

Even having the ID field in the database a get the error: Value of type 'Results<DBName>' has no member 'ID'. And I also can't access any other field.


Solution

  • realm.objects(DBName.self).filter("ID == %@", id)
    

    This returns all the DBName objects whose ID is id in a Results[doc]. So, the returned value is a list of objects. That is why the error says 'Results<DBName>' has no member 'ID'.

    If you are 100% sure you have one object in there, you can try to retrieve the first element this way. (For production, you should always use guard statement to prevent a crash as Jay suggests in the comment section.)

    realm.objects(DBName.self).filter("ID == %@", id).first!
    

    Or, if your ID is a primary key, you can do this.

    realm.object(ofType: DBName.self, forPrimaryKey: id)