Swift4 基础部分: Deinitialization(析构过程)

本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。

系列文章:

  • Swift4 基础部分:The Basics
  • Swift4 基础部分:Basic Operators
  • Swift4 基础部分:Strings and Characters
  • Swift4 基础部分:Collection Types
  • Swift4 基础部分:Control Flow
  • Swift4 基础部分:Functions
  • Swift4 基础部分:Closures
  • Swift4 基础部分: Enumerations
  • Swift4 基础部分: Classes and Structures
  • Swift4 基础部分: Properties
  • Swift4 基础部分: Methods
  • Swift4 基础部分: Subscripts
  • Swift4 基础部分: Inheritance
  • Swift4 基础部分: Initialization
A deinitializer is called immediately before a class 
instance is deallocated. You write deinitializers with the 
deinit keyword, similar to how initializers are written 
with the init keyword. Deinitializers are only available 
on class types.
  • 在一个类的实例被释放之前,析构函数被立即调用。用关键字deinit来标示析构函数,类似于初始化函数用init来标示。析构函数只适用于类类型。

例子:

class Bank {
    static var coinsInBank = 10_000;
    
    static func distribute(coins numberOfCoinsRequested: Int) -> Int {
        let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank);
        coinsInBank -= numberOfCoinsToVend;
        return numberOfCoinsToVend;
    }
    
    static func receive(coins: Int) {
        coinsInBank += coins;
    }
}

class Player {
    var coinsInPurse: Int;
    
    init(coins: Int) {
        coinsInPurse = Bank.distribute(coins: coins);
    }
    
    func win(coins: Int) {
        coinsInPurse += Bank.distribute(coins: coins);
    }
    
    deinit {
        Bank.receive(coins: coinsInPurse);
    }
}

var playerOne: Player? = Player(coins: 100);
print("A new player has joined the game with \(playerOne!.coinsInPurse) coins");
print("There are now \(Bank.coinsInBank) coins left in the bank");


playerOne!.win(coins: 2_000);
print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins");
print("The bank now only has \(Bank.coinsInBank) coins left");

playerOne = nil;
print("PlayerOne has left the game")
print("The bank now only has \(Bank.coinsInBank) coins left");

执行结果:

A new player has joined the game with 100 coins
There are now 9900 coins left in the bank
PlayerOne won 2000 coins & now has 2100 coins
The bank now only has 7900 coins left
PlayerOne has left the game
The bank now only has 10000 coins left

你可能感兴趣的:(Swift4 基础部分: Deinitialization(析构过程))