当声明在init阶段设置的属性时,是否应该将其设置为可选的?还是作为临时对象?
参见grimoireMemento
attribute:
可选示例:
class Kokoro{
private var emot:String = ""
var pain:[String:Int] = [:]
private var grimoireMemento:GrimoireMemento?
var toHeart:[String:String] = [:]
var fromHeart:[String:String] = [:]
var standBy:Bool = false
init(absDictionaryDB: AbsDictionaryDB) {
self.grimoireMemento = GrimoireMemento(absDictionaryDB: absDictionaryDB)
}
func getPain(biJuuName: String) -> Int {
return pain[biJuuName] ?? 0
}
func getGrimoireMemento()->GrimoireMemento{
return self.grimoireMemento!
}
}
与临时对象引用(我假设它将被垃圾收集器处理):
class Kokoro{
private var emot:String = ""
var pain:[String:Int] = [:]
var grimoireMemento:GrimoireMemento = GrimoireMemento(absDictionaryDB: AbsDictionaryDB())
var toHeart:[String:String] = [:]
var fromHeart:[String:String] = [:]
var standBy:Bool = false
init(absDictionaryDB: AbsDictionaryDB) {
self.grimoireMemento = GrimoireMemento(absDictionaryDB: absDictionaryDB)
}
func getPain(biJuuName: String) -> Int {
return pain[biJuuName] ?? 0
}
}
对于grimoireMemento
属性,应该使用两个示例中的哪一个?
类的所有存储属性-包括类的任何属性从父类继承的类必须在初始化。
这意味着您不需要考虑在初始化器之外分配备份默认值。你的两个代码片段在功能上不相似,但看起来你想要其中一个。
private(set) var grimoireMemento: GrimoireMemento
let grimoireMemento: GrimoireMemento