了解 Swift 个反初始化器

Understanding Swift Deinitializers

Swift deinitializer 没有更新 valueone 和 valuetwo,当我打印 mainTotal.sum 时我得到零作为答案,它应该更新值并将答案打印为 95 [=12] =]

struct mainTotal{
   static var valueone :Int = 0
   static var valuetwo :Int = 0
   static var sum :Int {
        get {
            return valueone + valuetwo
        }
    }
}

class Total{
    var valueone :Int = 10
    var valuetwo :Int = 10
    var sum :Int {
        get {
            return valueone + valuetwo
        }
    }
    func printsum(valueone:Int,valuetwo:Int){
        self.valueone += valueone
        self.valuetwo += valuetwo
    }
    deinit {
       mainTotal.valueone += valueone
       mainTotal.valuetwo += valuetwo

    }
}

var total = Total()
total.printsum(valueone: 10,valuetwo: 15)
var total1 = Total()
total1.printsum(valueone: 10,valuetwo: 20)
print(mainTotal.sum)
print(total.sum)
Total

deinit 未被调用,这就是 mainTotal 的值未更新的原因。

要调用 Totaldeinit,您需要手动释放 total 对象。

试试这个:

var total : Total? = Total()
total?.printsum(valueone: 10,valuetwo: 15)
print(total!.sum)
total = nil
print(mainTotal.sum)