정책을 통한 컴포지션
Coddy의 Rust 개발자를 위한 Swift 코스 레슨. 48개 중 38번째.
Rust에서는 트레이트로 제한된 제네릭 협력 객체나 동적 디스패치를 위한 dyn 트레이트 객체를 사용해 합성을 표현할 수 있습니다. 이 Presenter<F>는 구체적인 포매터 타입을 유지하고 필요한 메서드를 호출합니다. Swift의 any Formatter는 존재 타입 값을 저장하지만, 제네릭 Swift 매개변수는 API를 통해 구체적인 타입을 보존합니다. 두 설계 모두 타입 이름을 확인하거나 한 구현의 동작을 복제하는 대신 위임합니다. 예제에서는 뉴스를 대괄호로 감싸며, 인보이스 작업에서는 다른 요금 정책에 위임합니다. 사용자 지정 정책 구현은 자체 결과를 제어해야 하므로, 제공된 협력 객체를 하드코딩된 내장 공식으로 대체하지 마세요.
Rust
trait Formatter { fn format(&self, text: &str) -> String; }
struct Brackets;
impl Formatter for Brackets { fn format(&self, text: &str) -> String { format!("[{}]", text) } }
struct Presenter<F: Formatter> { formatter: F }
impl<F: Formatter> Presenter<F> { fn show(&self, text: &str) -> String { self.formatter.format(text) } }
fn main() {
let presenter = Presenter { formatter: Brackets };
println!("{}", presenter.show("news"));
}
Swift
protocol Formatter { func format(_ text: String) -> String }
struct Brackets: Formatter { func format(_ text: String) -> String { "[\(text)]" } }
struct Presenter {
let formatter: any Formatter
func show(_ text: String) -> String { formatter.format(text) }
}
print(Presenter(formatter: Brackets()).show("news"))챌린지
쉬움Policy 프로토콜을 charge(for units: Int) -> Int로 구현하세요. 요금이 요율과 단위 수의 곱인 FlatPolicy(rate:)를 구현하세요. 임의의 Policy를 저장하고, total(units:)에서 해당 Policy에 처리를 위임하는 Invoice(policy:)를 구현하세요. 사용자 지정 Policy도 작동해야 합니다. 입력의 요율은 0부터 100까지이고 단위 수는 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") }
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Rust 개발자를 위한 Swift의 모든 레슨
직접 연습해 보세요: Swift 플레이그라운드