Home > OS >  Covert ObjectId to String SwiftUI Realm object
Covert ObjectId to String SwiftUI Realm object

Time:11-18

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: 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

CodePudding user response:

If you only want the content of the ObjectId (the 24 char hex), you can use toHexString() function.

For example:

val _id = ObjectId("507f1f77bcf86cd799439011")
val idString = _id.toHexString()
println(idString)

That will print

507f1f77bcf86cd799439011

If instead, you actually want a String formed of "ObjectId("507f1f77bcf86cd799439011")", then you can create a simple extension function:

fun ObjectId.toSimpleString() = "ObjectId(\"${toHextString()}\")"

And then you could call it like this:

val _id = ObjectId("507f1f77bcf86cd799439011")
val idString = _id.toSimpleString()
println(idString)

That will print

ObjectId("507f1f77bcf86cd799439011")

CodePudding user response:

ObjectID's in Swift have a stringvalue property which returns the ObjectID as a string

You could do this

let idAsAsString = someRealmObject._id.stringValue

In SwiftUI, the id can be accessed in a similar way, and then use the value to init a new string

let x = someRealmObject._id.stringValue
let y = String(stringLiteral: x)
let _ = print(x, y)
Text("\(x) \(y)")

and the output will be

6376886a1dbb3c142318771c 6376886a1dbb3c142318771c

in the console and the same in the Text in the UI

Here's some SwiftUI showing the use

List {
    ForEach(myModel) { model in
        NavigationLink(destination: SecondView(navigationViewIsActive: $navigationViewIsActive, selectedEntryToShow: model))
        {
            Text("\(model._id.stringValue)")
        }
        
    }
}
  • Related