Search code examples
swiftdatabaserelational-databaseyapdatabase

Creating a unique ID for an object in YapDatabase


Suppose I have a collection of Users in a YapDatabase. How do I assign each user a unique identifier upon creation?

struct User: Codable{
     public var name: String
     private var id: ???
}

I've seen UUID in the Apple developer documentation. Having done some reasearch, it seems more for use in distributed systems, athough I suppose it could work. Are there other alternatives? Is there a "standard" method for giving objects a unique id in a relational database?


Solution

  • Possible variants:

    1) String (unique everywhere & forever)

    struct User: Codable{
         public var name: String
         private var id: String // = UUID().uuidString
    }
    

    2) Int (unique inside your users context, enough in majority of cases)

    struct User: Codable{
         public var name: String
         private var id: Int = 0 // = lastUser.id + 1, where 0 is a new non stored
    }