구조체와 독립적인 복사본
Coddy의 C++ 개발자를 위한 Swift 코스 레슨. 48개 중 26번째.
C++의 기본 멤버별 복사와 Swift의 구조체 대입은 각 필드의 의미를 보존합니다. std::string 멤버는 값을 복사하는 반면, shared_ptr 멤버는 동일한 피지시 대상에 대한 공유 소유권을 유지합니다. 이 예시에서 Swift의 String 값과 클래스 참조 필드도 이와 비슷한 차이가 있습니다. 복사본의 레이블을 변경해도 원래 레이블은 그대로지만, 공유 셀을 변경하면 두 복사본 모두에서 변경 사항이 보입니다. C++는 사용자 지정 복사 연산을 지원하므로 모든 클래스에 적용되는 보편적인 규칙은 아닙니다. 구조체를 변경하는 Swift 메서드에는 mutating이 필요합니다. 참조된 클래스 인스턴스를 수정해도 이를 담고 있는 구조체 필드는 대체되지 않습니다.
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>
struct Cell { std::string text; };
struct LabelledBox { std::string label; std::shared_ptr<Cell> shared; };
int main() {
LabelledBox original{"old", std::make_shared<Cell>(Cell{"one"})};
auto copy = original;
copy.label = "new";
copy.shared->text = "two";
std::cout << original.label << ' ' << original.shared->text << '\n';
}
Swift
완성된 프로그램 파일: Cell.swift.
final class Cell { var text: String; init(text: String) { self.text = text } }완성된 프로그램 파일: LabelledBox.swift.
struct LabelledBox { var label: String; var shared: Cell }완성된 프로그램 파일: main.swift.
let original = LabelledBox(label: "old", shared: Cell(text: "one"))
var copy = original
copy.label = "new"
copy.shared.text = "two"
print("\(original.label) \(original.shared.text)")챌린지
쉬움저장 프로퍼티 points: Int, init(points:), 그리고 amount를 더하는 mutating award(_ amount: Int)가 있는 값 타입 Score를 구현하세요. 입력은 초기 점수와 추가 점수이며, 각각 0부터 1000까지입니다. 원본을 복사하고 복사본에만 점수를 추가한 다음, 원본과 복사본의 점수를 공백으로 구분해 출력하세요.
필수 API와 solve(_ input: String) -> String을 구현하세요. 마지막 개행 없이 출력 텍스트를 반환하고, 편집 가능한 코드에서는 출력하지 마세요. 잠금된 드라이버는 추가로 유효한 입력에 대해 API를 독립적으로 확인한 다음, 반환된 텍스트를 정확히 하나의 개행과 함께 출력합니다. 모든 숫자 연산은 Int 범위 안에서 이루어집니다.
코드는 Score.swift, Functions.swift에 작성하세요. main.swift에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.
직접 해보기
import Foundation
func apiChecks(_ input: String) -> Bool {
let original = Score(points: 13); var copy = original; copy.award(6); copy.award(2); return original.points == 13 && copy.points == 21
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// PUBLIC API 검사 시작
let apiOK = apiChecks(input)
// PUBLIC API 검사 종료
if apiOK { print(solve(input)) } else { print("API mismatch") }
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 Swift의 모든 레슨
직접 연습해 보세요: Swift 플레이그라운드