Search code examples
iosmodelrealmoverridingswift4

swift4 realm model - override description (java toString() equivalent)


I have a problem. I am trying to override description method to print reference values as I want. I read that this is equivalent to Java toString() method (I am new to swift)

The problem is that, it is not working and I can't find any solution for that. I did it exactly as in examples.. What did I do wrong?

Here's my code:

import Foundation
import RealmSwift

@objcMembers class Patient: Object{

    //toString()
    override var description: String{
        return "Patient: Ref nr: \(self.referenceNumber), First name: \(self.firstName), Surname: \(self.surname) Email:  \(self.email)"
    }

    var patientId:Int{
        return self.patientId
    }
    dynamic var referenceNumber: String = ""
    dynamic var firstName:String = ""
    dynamic var surname:String = ""
    dynamic var email:String = ""

    convenience init(referenceNumber:String, firstName:String, surname:String, email:String) {
        self.init()
        self.referenceNumber = referenceNumber
        self.firstName = firstName
        self.surname = surname
        self.email = email
    }

Now, whenever I try to print that: (I posted more code in case smith wrong is earlier than printing)

var patient: Results<Patient>!

override func viewDidLoad() {
    super.viewDidLoad();

    let realm = RealmService.shared.realm
    let patient = realm.objects(Patient.self) //tocheck: can I get only one element from Realm and set to store only 1 element?

    //HERE IT GOES WRONG
    print(patient) //case 1
    print(patient.description) //case 2
}

It prints in the console that: (in both cases the same)

Results<Patient> <0x7fccaaf03b90> (
    [0] Patient {
        referenceNumber = 231321;
        firstName = James;
        surname = Rodriguez;
        email = [email protected];
    }
)

WHY?


Solution

  • Your implementation for the String description in your object is right. It is a correct Computed Property. As such, Realm will ignore it for storage, but it is still available for you to use it.

    When you're invoking let patient = realm.objects(Patient.self) the Realm is giving you a Results<Patient> object. Think of it as an Array of Patient objects. So, for example if you're looking for the description of the first element it is possible to get it as you would do it in an Array:

    if let firstPatient = realm.objects(Patient.self).first {
        print(firstPatient.description)
    }
    

    For a very good reference on this subject check out the Realm docs for Results.