Swift教程之类的析构详解

2020-01-08 22:48:00王振洲

println(“PlayerOne won 2000 coins & now has     (playerOne!.coinsInPurse) coins”)
// 输出 “PlayerOne won 2000 coins & now has 2100 coins”
println(“The bank now only has (Bank.coinsInBank) coins left”)
// 输出 “The bank now only has 7900 coins left”

 

这里,player 已经赢得了 2,000 硬币。player 的钱包现在有 2,100 硬币,bank 只剩余 7,900 硬币。

复制代码
playerOne = nil
println(“PlayerOne has left the game”)
// 输出 “PlayerOne has left the game”
println(“The bank now has (Bank.coinsInBank) coins”)
// 输出 “The bank now has 10000 coins”
玩家现在已经离开了游戏。这表明是要将可选的playerOne变量设置为nil,意思是“没有Player实例”。当这种情况发生的时候,playerOne变量对Player实例的引用被破坏了。没有其它属性或者变量引用Player实例,因此为了清空它占用的内存从而释放它。在这发生前一步,其析构函数被自动调用,其硬币被返回到银行。

注:相关教程知识阅读请移步到swift教程频道。