2017-05-26 43 views
0

有什么方法可以为可选属性的Realm类制作组合键?可选属性的领域Swift组合键

例如:

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)" 
    } 
} 

当我写我这样的代码,编译器会抱怨,我不能分配给我的恒定性并建议我改变“让”到“变种”;不过,根据Realm Swift Documentation,我需要将可选属性设置为常量。

我不确定这是甚至可能的,因为我在Realm文档中找不到关于可选主键的任何内容。

回答

2

您需要设置RealmOptionalvalue成员。 RealmOptional属性不能为var,因为Realm无法检测到不能由Objective-C运行时表示的属性类型的分配,这就是为什么RealmOptional,ListLinkingObjects属性必须都是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)" 
    } 
}