用于可选属性的Realm Swift复合键

时间:2017-05-26 22:20:43

标签: swift realm

有没有办法为具有可选属性的Realm类创建复合键?

例如:

class Item: Object {
    dynamic var id = 0
    let importantNumber = RealmOptional<Int>()
    let importantNumber2 = RealmOptional<Int>()

    func setCompoundID(id: Int) {
        self.id = id
        compoundKey = compoundKeyValue()
    }

    func setCompoundImportantNumber(importantNumber: Int) {
        self.importantNumber = importantNumber
        compoundKey = compoundKeyValue()
    }

    func setCompoundImportantNumber2(importantNumber2: Int) {
        self.importantNumber2 = importantNumber2
        compoundKey = compoundKeyValue()
    }

    dynamic lazy var compoundKey: String = self.compoundKeyValue()

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

    func compoundKeyValue() -> String {
        return "\(id)\(importantNumber)\(importantNumber2)"
    }
}

当我编写这样的代码时,编译器会抱怨我无法分配给我的常量属性,并建议我更改“让”和“#”;到&#39; var&#39 ;;但是,根据Realm Swift Documentation,我需要将可选属性设置为常量。

我不确定这是否可行,因为我无法在Realm文档中找到有关可选主键的任何内容。

1 个答案:

答案 0 :(得分:2)

您需要设置RealmOptional&n; value成员。 RealmOptional属性不能为var,因为Realm无法检测到Objective-C运行时无法表示的属性类型的分配,这就是RealmOptionalList的原因LinkingObjects属性必须全部为let

class Item: Object {
    dynamic var id = 0
    let importantNumber = RealmOptional<Int>()
    let importantNumber2 = RealmOptional<Int>()

    func setCompoundID(id: Int) {
        self.id = id
        compoundKey = compoundKeyValue()
    }

    func setCompoundImportantNumber(importantNumber: Int) {
        self.importantNumber.value = importantNumber
        compoundKey = compoundKeyValue()
    }

    func setCompoundImportantNumber2(importantNumber2: Int) {
        self.importantNumber2.value = importantNumber2
        compoundKey = compoundKeyValue()
    }

    dynamic lazy var compoundKey: String = self.compoundKeyValue()

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

    func compoundKeyValue() -> String {
        return "\(id)\(importantNumber)\(importantNumber2)"
    }
}