swft deinit

swift deinit

/*

    deinit only for class

    by Default the ARC(automatic reference counting) manage your deinit

    but sometimes for example you want to close a file writing process first

 */


class CoinBank{

    static var CoinDeposit = 1000

    static func distribute(Coin:Int)->Int{

        if Coin > CoinDeposit {

            print("Don't have enough Coin in Coin bank, return\(CoinDeposit)")

            return CoinDeposit

        }else{

            CoinDeposit -= Coin

            return Coin

        }

    }

    static func receive(Coin:Int)->Int{

        CoinDeposit += Coin

        if CoinDeposit > 1000{

            print("Coin bank exceeds deposit limit, force remove the surplus amount")

            CoinDeposit = 1000

            return CoinDeposit

        }else{

            return CoinDeposit

        }

    }

}


class Player{

    var CoinInPurse:Int

    init(Coin:Int){

        CoinInPurse=CoinBank.distribute(Coin: Coin)

    }

    func win(WinCoin:Int)->Int{

        CoinInPurse += WinCoin

        return WinCoin

    }

    func lose(LoseCoin:Int)->Int{

        CoinInPurse -= LoseCoin

        return LoseCoin

    }

    deinit{

        CoinBank.receive(Coin: CoinInPurse)

    }

}


var PlayerA = Player(Coin: 100)


print(CoinBank.CoinDeposit)


var PlayerB:Player? = Player(Coin:500)


print(CoinBank.CoinDeposit)


PlayerB!.win(WinCoin: 1000)


print(CoinBank.CoinDeposit)


PlayerB = nil





你可能感兴趣的:(swift_杂碎)