swift Deinitializer没有更新ValueOne和valuetwo,当我打印Maintotal.sum时,我将获得零作为答案,它应该更新值并将答案打印为95
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
的值未更新的原因。
要调用Total
的deinit
,您需要手动对 total
对象进行处理。
尝试以下操作:
var total : Total? = Total()
total?.printsum(valueone: 10,valuetwo: 15)
print(total!.sum)
total = nil
print(mainTotal.sum)