styler1972 styler1972 - 5 months ago 69
Swift Question

Realm.io and compound primary keys

I'm using Realm for Swift 1.2, and I'm wondering how to implement a compound primary key for an entity.

So you specify your primary key by overriding

primaryKey()


override static func primaryKey() -> String? { // <--- only 1 field
return "id"
}


The only way I can see is to create another compound attribute like so

var key1 = "unique thing"
var key2 = 123012

lazy var key: String? = {
return "\(self.key1)\(self.key2)"
}()

override static func primaryKey() -> String? {
return "key"
}


How do you properly supply compound keys in Realm?

Answer

It appears that is the correct way to return a compound key in Realm.

Here's the answer from Realm : https://github.com/realm/realm-cocoa/issues/1192

You could use a mix of lazy and didSet instead to have the compoundKey property be both derived and stored:

public final class Card: Object {
    public dynamic var id = 0 {
        didSet {
            compoundKey = compoundKeyValue()
        }
    }
    public dynamic var type = "" {
        didSet {
            compoundKey = compoundKeyValue()
        }
    }
    public dynamic lazy var compoundKey: String = self.compoundKeyValue()
    public override static func primaryKey() -> String? {
        return "compoundKey"
    }

    private func compoundKeyValue() -> String {
        return "\(id)-\(type)"
    }
}

// Example

let card = Card()
card.id = 42
card.type = "yolo"
card.compoundKey // => "42-yolo"
Comments