정책을 통한 합성
Coddy의 C 개발자를 위한 Swift 코스 레슨. 48개 중 38번째.
C에서는 함수 포인터나 콜백 인터페이스를 다른 구조체 안에 저장할 수 있습니다. Swift에서는 프로토콜을 준수하는 타입 중에서 런타임에 동작을 선택하기 위해 existential any Protocol 값을 저장할 수 있습니다. 저장된 준수 타입은 값 타입일 수도 있고 클래스 참조일 수도 있습니다.
두 예제 모두 notice는 제공된 formatter에 처리를 위임합니다. C에서는 출력 버퍼와 그 용량을 명시적으로 전달하고, Swift에서는 관리되는 String을 반환합니다. 대신 제네릭 Swift 설계에서는 정책 타입을 매개변수로 바인딩할 수 있지만, 이 existential을 사용하면 하나의 인터페이스 뒤에서 런타임에 선택할 수 있습니다.
C: 완전한 프로그램
formatter.h
#ifndef FORMATTER_H
#define FORMATTER_H
#include <stddef.h>
typedef struct { void (*format)(const char *, char *, size_t); } Formatter;
#endif
brackets.h
#ifndef BRACKETS_H
#define BRACKETS_H
#include <stdio.h>
#include "formatter.h"
static void brackets(const char *text, char *output, size_t capacity) { snprintf(output, capacity, "[%s]", text); }
#endif
notice.h
#ifndef NOTICE_H
#define NOTICE_H
#include "formatter.h"
typedef struct { Formatter formatter; } Notice;
static void notice_render(const Notice *notice, const char *text, char *output, size_t capacity) {
notice->formatter.format(text, output, capacity);
}
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "brackets.h"
#include "notice.h"
int main(void) {
Notice notice = {{brackets}};
char output[32];
notice_render(¬ice, "ready", output, sizeof output);
puts(output);
return 0;
}
Swift: 완전한 프로그램
Formatter.swift
import Foundation
protocol Formatter { func format(_ text: String) -> String }Brackets.swift
import Foundation
struct Brackets: Formatter {
func format(_ text: String) -> String { "[" + text + "]" }
}Notice.swift
import Foundation
struct Notice {
let formatter: any Formatter
func render(_ text: String) -> String { formatter.format(text) }
}main.swift
import Foundation
let notice = Notice(formatter: Brackets())
print(notice.render("ready"))콜백 또는 프로토콜 호출은 그대로 유지하세요. 이를 샘플 구현 하나의 알려진 수식으로 바꾸면 다른 유효한 정책을 제공하는 호출자가 제대로 동작하지 않게 됩니다.
챌린지
쉬움Policy 프로토콜을 charge(for units: Int) -> Int로 구현하세요. 요금이 rate에 units를 곱한 값인 FlatPolicy(rate:)를 구현하세요. 임의의 Policy를 저장하고 해당 정책에 처리를 위임하는 total(units:)를 갖춘 Invoice(policy:)를 구현하세요. 사용자 지정 정책도 작동해야 합니다. 입력값은 rate가 0부터 100까지이고 units가 0부터 100까지입니다. 출력은 청구서 총액입니다.
필수 API와 solve(_ input: String) -> String을 구현하세요. 마지막 개행 없이 출력 텍스트를 반환하고, 편집 가능한 코드에서는 출력하지 마세요. 잠긴 드라이버는 추가로 유효한 입력에서 API를 독립적으로 확인한 다음, 반환된 텍스트를 정확히 하나의 개행과 함께 출력합니다. 모든 숫자 연산은 Int 범위 내에서 이루어집니다.
코드는 Policy.swift, FlatPolicy.swift, Invoice.swift, Functions.swift에 작성하세요. main.swift에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.
직접 해보기
import Foundation
func apiChecks(_ input: String) -> Bool {
struct ProbePolicy: Policy { func charge(for units: Int) -> Int { units + 9 } }
return FlatPolicy(rate: 7).charge(for: 3) == 21 && Invoice(policy: ProbePolicy()).total(units: 4) == 13 && Invoice(policy: FlatPolicy(rate: 2)).total(units: 5) == 10
}
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 플레이그라운드