反初始化函数

前端之家收集整理的这篇文章主要介绍了反初始化函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

//: Playground - noun: a place where people can play

import UIKit

//这里是一个反初始化函数操作的例子。

struct Bank {

static var coinsInBank = 10_000

func vendCoins(var numberOfCoinsToVend: Int) -> Int {

numberOfCoinsToVend = min(numberOfCoinsToVend,coinsInBank)

coinsInBank -= numberOfCoinsToVend

return numberOfCoinsToVend

}

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)

playerOne?.coinsInPurse

Bank.coinsInBank


playerOne?.winCoins(2_000)

playerOne?.coinsInPurse

Bank.coinsInBank

playerOne = nil

Bank.coinsInBank

原文链接:https://www.f2er.com/swift/326784.html

猜你在找的Swift相关文章