티스토리 뷰

출처

http://kka7.tistory.com/20



해제 (Deinitialization)

Swift 는 인스턴스가 더 이상 필요하지 않을 때
자동적으로 해제해주고 자원을 돌려준다.

ARC  로 인스턴스의 메모리를 관리한다.
일반적으로는 수동으로 수행할 필요가 없다.

하지만 리소스 작업할 때 몇 가지 추가적인 정리가 필요할 때가 있다. 
그 때 사용한다.

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")

// Prints "A new player has joined the game with 100 coins"


print("There are now \(Bank.coinsInBank) coins left in the bank")

// Prints "There are now 9900 coins left in the bank"


playerOne!.win(coins: 2_000)

print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")

// Prints "PlayerOne won 2000 coins & now has 2100 coins"


print("The bank now only has \(Bank.coinsInBank) coins left")

// Prints "The bank now only has 7900 coins left"


playerOne = nil

print("PlayerOne has left the game")

// Prints "PlayerOne has left the game"


print("The bank now has \(Bank.coinsInBank) coins")

// Prints "The bank now has 10000 coins"







'iOS 개발 > Swift' 카테고리의 다른 글

[Swift 3] 제네릭 (Generics)  (0) 2017.04.16
[Swift 3] 프로토콜 (Protocols)  (0) 2017.04.16
[Swift 3] 초기화 (Initialzer)  (0) 2017.04.15
[Swift 3] 상속 (Inheritance)  (0) 2017.04.15
[Swift 3] 서브스크립트 (Subscript)  (0) 2017.04.15
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함