Swift - Convert ObjectID to String

how to convert ObjectID to String.
My model _id is of type ObjectID, while the logic applied on it is of String

If you want the ObjectId value as a string it’s


So if your object looks like this

class PersonClass: Object {
   @objc dynamic var _id = ObjectId.generate()

and you want to get the value at a later time

let idValue = person._id.stringValue

I’ m getting the following error when im trying to convert string to ObjectID
Error Domain=io.realm Code=13 “Invalid Object ID string ‘Jr75EHNYqYhOJgyiUGcMGPXVsk12’: must be 24 hex digits” UserInfo={NSLocalizedDescription=Invalid Object ID string ‘Jr75EHNYqYhOJgyiUGcMGPXVsk12’: must be 24 hex digits}

That’s different than the original question, which was asking from ObjectID to a String

So this is a different question?

If you want to initialize an objectId with a string it’s this


Which can be found in the Swift API Reference for ObjectId Class Reference

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.