Home > Blockchain >  swift (xcode) is it better to use optional or a temporary object?
swift (xcode) is it better to use optional or a temporary object?

Time:07-03

When declaring an attribute that is set at the init stage, should it be set as an optional? Or as a temporary object ?

See grimoireMemento attribute:

optional example :

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!
    }
}

Versus a temporary object reference (which I assume will be disposed by the garbage collector):

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

For the grimoireMemento attribute which of the 2 examples should be used?

CodePudding user response:

All of a class’s stored properties—including any properties the class inherits from its superclass—must be assigned an initial value during initialization.

That means you don't need to think about assigning a backup default outside of an initializer. Your two code snippets are not functionally similar but it seems like you want one of these.

private(set) var grimoireMemento: GrimoireMemento
let grimoireMemento: GrimoireMemento
  • Related