swiftkotlinrealmkotlin-multiplatformrealm-mobile-platform

Covert ObjectId to String SwiftUI Realm object


I have my model called Restaurant: realm object on kotlin:

class Restaurant : RealmObject {
    @PrimaryKey
    var _id: ObjectId = ObjectId.create()
    var name: String = ""
    var adress: String? = null
}

I want to use the _id property. But for that I need to convert to a String in SwiftUI

I tried: restaurant_id as! String, it does not work,

Is is related to this post: https://www.mongodb.com/community/forums/t/swift-convert-objectid-to-string/121829

No real answers there

Any other solutions? the error when using .toHexString(): Value of type 'any Library_baseObjectId' has no member 'toHexString':

enter image description here

the type of _id in this case: enter image description here

The error when trying: "\(restaurant._id.stringValue)"

enter image description here


Solution

  • I solved this by adding a getter to the class:

    class Restaurant : RealmObject {
        @PrimaryKey
        var _id: ObjectId = ObjectId.create()
        var name: String = ""
        var adress: String? = null
    
        fun getID() : String{
                return _id.toString()
            }
    }