티스토리 뷰

Deinitializer는 Initializer와는 반대로 클래스 인스턴스가 소멸되기 직전에 호출한다. 디이니셜라이저는 오직 클래스 타입에서만 사용할 수 있으며, 선언을 위해 deinit 키워드를 사용한다.

 

일반적으로 swift가 자원의 해제를 자동으로 알아서 해주는데, 열었던 파일을 사용이 끝나고 닫는 것 같이 사용자가 자원 해지를 위해 수동으로 작업 해야하는 경우도 있다. 디이니셜라이저는 클래스당 오직 하나만 선언할 수 있고 파라미터를 받을 수 없다. 

 

기본적인 형태는 다음과 같다.

deinit {
    // perform the deinitialization
}

디이니셜라이저는 자동으로 호출되고 수동으로 호출할 수 없다. 부모 클래스의 디이니셜라이저는 자식 클래스에서 따로 선언하지 않아도 자동으로 호출된다.

 

바로 예제를 하나 보자.

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"
// 사용자는 100 코인을 갖고 시작합니다.
print("There are now \(Bank.coinsInBank) coins left in the bank")
// Prints "There are now 9900 coins left in the bank"
// 현 시점에 은행은 9900의 코인을 소유하고 있습니다.

playerOne!.win(coins: 2_000)
print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
// Prints "PlayerOne won 2000 coins & now has 2100 coins"
// 사용자가 게임에 이겨 2000코인을 받아 처음에 갖고 있던 100 코인과 더불어 현재 총 2100 코인을 소유하게 됩니다.
print("The bank now only has \(Bank.coinsInBank) coins left")
// Prints "The bank now only has 7900 coins left"
// 사용자에게 2100 코인을 나눠준 은행에는 현재 7900 코인이 남았습니다.

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"

플레이어가 접속하거나 게임에서 이기면 은행이 돈을 주고, 플레이어 객체가 자원 할당이 해지되면 해당 플레이어가 가지고 있던 돈을 모두 은행에 반납하도록 deinit을 구현한 예제이다.

 

끝!

Comments