Swift 会自动释放不再需要的实例以释放资源。Swift 通过自动引用计数(ARC)处理实例的内存管理。
通常当你的实例被释放时不需要手动地去清理。但是,当使用自己的资源时,你可能需要进行一些额外的清理。
例如,如果创建了一个自定义的类来打开一个文件,并写入一些数据,你可能需要在类实例被释放之前关闭该文件。
在类的定义中,每个类最多只能有一个析构函数。析构函数不带任何参数,在写法上不带括号:
deinit { // 执行析构过程}
实例:
struct Bank { static var coinsInBank = 10_000 static func vendCoins(var numberOfCoinsTovend: Int) -> Int { numberOfCoinsTovend = min(numberOfCoinsTovend,coinsInBank) coinsInBank -= numberOfCoinsTovend return numberOfCoinsTovend } static func receiveCoins(coins: Int) { coinsInBank += coins }}class Player { var coinsInPurse: Int init(coins: Int) { coinsInPurse = Bank.vendCoins(coins) } func winCoins(coins: Int) { coinsInPurse += Bank.vendCoins(coins) } deinit { Bank.receiveCoins(coinsInPurse) }}var playerOne: Player? = Player(coins: 100)print("A new player has joined the game with \(playerOne!.coinsInPurse) coins")// 输出 "A new player has joined the game with 100 coins"print("There are Now \(Bank.coinsInBank) coins left in the bank")// 输出 "There are Now 9900 coins left in the bank"playerOne!.winCoins(2_000)print("PlayerOne won 2000 coins & Now has \(playerOne!.coinsInPurse) coins")// 输出 "PlayerOne won 2000 coins & Now has 2100 coins"print("The bank Now only has \(Bank.coinsInBank) coins left")// 输出 "The bank Now only has 7900 coins left"playerOne = nilprint("PlayerOne has left the game")// 输出 "PlayerOne has left the game"print("The bank Now has \(Bank.coinsInBank) coins")// 输出 "The bank Now has 10000 coins"总结
以上是内存溢出为你收集整理的swift2 析构过程全部内容,希望文章能够帮你解决swift2 析构过程所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)