How to set primary key in Swift for Realm model How to set primary key in Swift for Realm model swift swift

How to set primary key in Swift for Realm model


primaryKey needs to be a class function which returns the name of the property which is the primary key, not an instance method which returns the value of the primary key.

@objcMembers class Foo: RLMObject {    dynamic var id = 0    dynamic var title = ""    override class func primaryKey() -> String? {        return "id"    }}


The return type of primaryKey() is optional:

class Foo: RLMObject {    dynamic var id = 0    dynamic var title = ""    override class func primaryKey() -> String? {        return "id"    }}


For Swift 5:

import RealmSwift     class Signature: Object {           @objc dynamic var id = ""            override static func primaryKey() -> String? {                return "id"            }      }

To avoid: Terminating app due to uncaught exception 'RLMException', reason: 'Primary key property 'id' does not exist on object.