title: How can I generate ids for objects in RealmSwift?
body: <p>I am using RealmSwift. What is the best / canonical way to generate ids for objects?</p>
  
  <p>Here is what I came up with:</p>
  
  <pre><code>class MyObject: Object {
      dynamic var id = ""
      dynamic var createdAt = NSDate()
  
      override class func primaryKey() -&gt; String {
          return "id"
      }
  
      func save() {
          let realm = try! Realm()
  
          if(self.id == "") {
              while(true) {
                  let newId = NSUUID().UUIDString
                  let saying = realm.objectForPrimaryKey(MyObject.self, key: newId)
                  if(saying == nil) {
                      self.id = newId
                      break
                  }
              }
          }
  
          try! realm.write {
              realm.add(self)
          }
      }
  }
  </code></pre>
  
  <p>I wanted a function that persists the object to Realm and either overwrites or creates a new one based on the id.  This seems to work ok, but I wasn't sure if there was something built into realm to do this.  Or is there a better way?</p>
  
  <p>Thanks.</p>