도구
로그인
한국어

코드 배우기Swift

Swift 캡슐화

Swift 6.4 기준

Swift 의 private(set), willSet·didSet, 계산 속성과 throws 를 은행 계좌 예제로 익혀요.

한 줄 뜻

객체의 값을 아무나 바꾸지 못하게 숨기고, 정해 둔 메서드로만 바꾸게 하는 것이에요. Swift 는 읽기와 쓰기를 따로 닫을 수 있어요(private(set)).

왜 필요한가

잔액이 그냥 var 면 앱 어디서든 balance -= 400_000 한 줄로 음수 잔액을 만들어요. 출금 규칙을 메서드에 사용해 두어도 그 메서드를 안 거치면 소용이 없어요.

쓰기를 클래스 안으로 숨기면 잔액이 바뀌는 길은 deposit 과 withdraw 둘뿐이에요. 규칙 검사, 기록 남기기, 잘못된 요청 알리기를 그 두 곳과 didSet 에만 두면 돼요.

일상 비유

은행 창구를 떠올려 보세요. 잔액 화면은 누구나 볼 수 있지만, 금고 안 돈을 옮기는 건 창구 직원만 해요. 직원은 돈을 옮길 때마다 장부(didSet)에 적고, 잔액보다 많이 찾으려 하면 거절 쪽지(throw)를 내밀어요.

속성을 아무나 바꾸게 열어 두면 생기는 버그

let acct = Account(owner: "Doyun")acct.balance = 150_000acct.balance -= 400_000acct.owner = ""print("[\(acct.owner)] \(acct.balance) won") final class Account {    var owner: String    var balance = 0     init(owner: String) {        self.owner = owner    }}

실행하면

[] -250000 won

balance 와 owner 가 그냥 var 라서 밖에서 고쳐요. 15만 원 있는 계좌에서 40만 원을 빼도 막는 곳이 없어 -25만 원이 됐어요.

주인 이름도 빈 글자가 됐어요. 이런 줄이 여러 파일에 흩어져 있으면 잔액을 망가뜨린 곳을 찾기 어려워요.

예제 코드

main.swift · 65줄
import Foundation let acct = Account(owner: "Doyun")acct.memo = "  rent money  "do {    try acct.deposit(150_000)    try acct.withdraw(400_000)    print("not printed")} catch AccountError.notEnough(let short) {    print("short by \(short) won")} catch {    print("other error: \(error)")}do {    try acct.withdraw(60_000)} catch {    print("other error: \(error)")}print("\(acct.memo): \(acct.balance) won, low: \(acct.isLow)")print("history: \(acct.history)") enum AccountError: Error {    case notPositive    case notEnough(short: Int)} final class Account {    let owner: String    private(set) var history: [Int] = []    private(set) var balance = 0 {        willSet {            print("balance \(balance) -> \(newValue)")        }        didSet {            history.append(balance - oldValue)        }    }    var memo = "" {        didSet {            memo = memo.trimmingCharacters(in: .whitespaces)        }    }    var isLow: Bool {        balance < 100_000    }     init(owner: String) {        self.owner = owner    }     func deposit(_ amount: Int) throws {        guard amount > 0 else {            throw AccountError.notPositive        }        balance += amount    }     func withdraw(_ amount: Int) throws {        let short = amount - balance        guard short <= 0 else {            throw AccountError.notEnough(short: short)        }        balance -= amount    }}

언제 사용하나

  • 값을 읽는 건 괜찮지만 바꾸는 데는 규칙이 있을 때(private(set) + 메서드)
  • 값이 바뀔 때마다 할 일이 있을 때(기록, 화면 새로 그리기)는 didSet
  • 요청을 처리할 수 없을 때 까닭과 함께 알려야 하면 throws 와 오류 enum

willSet 에서는 새 값이 newValue, didSet 에서는 옛 값이 oldValue 라는 이름으로 들어와요. 처음 init 에서 넣는 값에는 둘 다 불리지 않아요.

계산 속성(var isLow: Bool { ... })은 저장 칸이 없어서 다른 값과 어긋날 일이 없어요.

자주 하는 실수

바꾸는 문을 그냥 열어 둠

var coins 는 누구든 -30 을 넣을 수 있어요. 읽기는 열고 쓰기는 private(set) 으로 닫은 다음, 왜 바뀌는지 이름이 드러나는 메서드(add)에서 검사해요.

틀린 코드

let wallet = Wallet()wallet.coins = -30print(wallet.coins) final class Wallet {    var coins = 0}

실행하면-30

고친 코드

let wallet = Wallet()wallet.add(-30)print(wallet.coins) final class Wallet {    private(set) var coins = 0     func add(_ amount: Int) {        if amount > 0 {            coins += amount        }    }}

실행하면0

private(set) 속성에 밖에서 값을 넣음

읽기는 되지만 사용하는 문(setter)은 클래스 안에만 있으니 컴파일러가 막아요. 잔액을 늘리려면 검사가 들어 있는 deposit 을 거쳐요. try? 는 오류가 나면 그냥 nil 로 넘기는 짧은 꼴이에요.

틀린 코드

let acct = Account(owner: "Eun")acct.balance = 1_000_000

Swift 컴파일러가 내는 오류error: cannot assign to property: 'balance' setter is inaccessible

고친 코드

let acct = Account(owner: "Eun")try? acct.deposit(1_000)print(acct.balance)

실행하면balance 0 -> 1000 1000

throws 메서드를 try 없이 부름

throws 가 붙은 메서드는 오류를 던질 수 있다는 약속이라, 부르는 쪽이 try 를 붙이고 do·catch 로 받을 곳을 정해야 해요. 자바처럼 어떤 오류인지 적지 않아도 되지만, 던질 수 있다는 사실은 부르는 줄에 드러나요.

틀린 코드

let acct = Account(owner: "Eun")acct.deposit(500)

Swift 컴파일러가 내는 오류error: call can throw but is not marked with 'try'

고친 코드

let acct = Account(owner: "Eun")do {    try acct.deposit(-500)} catch {    print("refused: \(error)")}

실행하면refused: notPositive

확인 문제

문제 1

새 계좌의 isLow 는 무엇일까요?

let a = Account(owner: "Jin")print(a.isLow)

답과 까닭 보기

답: 1. true 잔액이 0 이라 balance < 100_000 이 참이에요. 계산 속성은 만든 순간부터 읽을 때마다 새로 따져요.

문제 2

빈칸을 붙여 memo 에 넣었어요. 무엇이 찍힐까요?

let a = Account(owner: "Jin")a.memo = "  car  "print("[\(a.memo)]")

답과 까닭 보기

답: 2. [car] memo 의 didSet 이 넣자마자 앞뒤 빈칸을 다듬어요. 읽을 때는 이미 car 예요.

자주 묻는 것

private(set) 은 무엇인가요?

읽기와 쓰기의 범위를 따로 정하는 꼴이에요. private(set) var balance 는 누구나 읽지만 값을 바꾸는 건 그 형식 안에서만 돼요. public private(set) 처럼 둘을 짝지어 사용하기도 해요.

willSet 과 didSet 은 언제 불리나요?

저장 속성의 값이 바뀌기 바로 전에 willSet, 바로 뒤에 didSet 이 불려요. willSet 안에서는 새 값이 newValue, didSet 안에서는 옛 값이 oldValue 예요. init 에서 처음 넣는 값에는 불리지 않아요.

오류를 던질 때 어떤 형식을 사용해야 하나요?

Error protocol 을 따르는 enum 이 흔해요. case 마다 상황을 나누고, 모자란 금액처럼 필요한 값을 연관 값으로 실어요. 받는 쪽은 catch 에서 case 별로 나눠 받아요.