Menu
CoddyTech

접근 제어와 불변 조건

Coddy의 C++ 개발자를 위한 Swift 코스 레슨. 48개 중 39번째.

공개(public) const 게터를 가진 C++ private 멤버는 변이(mutation)를 메서드 뒤에 두면서 관찰을 노출할 수 있습니다. Swift의 private(set) 역시 비슷하게 읽기 접근과 세터 접근을 분리하며, private, fileprivate, internal, public, open 수준은 Swift 선언, 파일 및 모듈 경계를 사용합니다. C++ private 및 protected는 Swift 모듈 가시성 대신 클래스 규칙을 따릅니다. 두 예제 모두 텍스트가 변경될 때만 revision을 증가시켜 반복되는 동일한 업데이트에 대해 불변성을 유지합니다. const 게터는 메서드 계약이며 보편적인 심층 불변성(deep-immutability)을 보장하지 않습니다. 관련 필드를 함께 업데이트하는 책임을 변이 연산에 유지하세요.

C++

전체 프로그램 파일: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
class Draft {
    std::string text;
    int revision_ = 0;
public:
    int revision() const { return revision_; }
    void replace(const std::string &value) { if (value == text) return; text = value; ++revision_; }
};

int main() {
Draft draft;
    draft.replace("hello");
    draft.replace("hello");
    std::cout << draft.revision() << '\n';
}

Swift

전체 프로그램 파일: Draft.swift.

struct Draft {
    private var text = ""
    private(set) var revision = 0
    mutating func replace(_ value: String) {
        guard value != text else { return }
        text = value
        revision += 1
    }
}

전체 프로그램 파일: main.swift.

var draft = Draft()
draft.replace("hello")
draft.replace("hello")
print(draft.revision)
challenge icon

챌린지

쉬움

호출자 기준 읽기 전용인 balance와 spend(_ amount: Int) -> Bool을 포함하는 Wallet(initial:)을 구현하세요. 0 이하이거나 잔액을 초과하는 지출은 잔액을 변경하지 않고 거부하며, 그렇지 않은 경우에는 차감하고 true를 반환하세요. 초기 잔액은 0 이상입니다. 입력은 0부터 1000까지의 초기 잔액과 이어서 0개부터 30개까지의 -10부터 1000까지의 지출 금액으로 구성됩니다. 최종 잔액, 공백 한 칸, 성공한 지출 횟수를 출력하세요.

필요한 API와 solve(_ input: String) -> String을 구현하세요. 마지막 줄바꿈 없이 출력 텍스트를 반환하세요. 편집 가능한 코드 내에서 출력(print)하지 마세요. 잠긴 드라이버는 추가적인 유효한 입력에 대해 독립적으로 API를 검사한 후 반환된 텍스트를 정확히 하나의 줄바꿈과 함께 출력합니다. 모든 숫자 연산은 Int 범위 내에 유지됩니다.

작성할 코드는 Wallet.swift, Functions.swift에 들어갑니다. main.swift는 제공된 입출력 코드를 포함하며 수정할 수 없습니다.

직접 해보기

import Foundation
func apiChecks(_ input: String) -> Bool {
let w = Wallet(initial: 17); guard !w.spend(18) && !w.spend(0) && !w.spend(-1) && w.balance == 17 else { return false }; return w.spend(7) && w.balance == 10 && w.spend(10) && w.balance == 0 && !w.spend(1)
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 공개 API 프로브 시작
let apiOK = apiChecks(input)
// 공개 API 프로브 종료
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 Swift의 모든 레슨

직접 연습해 보세요: Swift 플레이그라운드