Menu
CoddyTech

정책을 통한 합성

Coddy의 PHP 개발자를 위한 Swift 코스 레슨. 48개 중 38번째.

PHP의 컴포지션은 인터페이스 형식의 협력 객체를 저장하고 해당 객체에 위임할 수 있습니다. 렌더러는 실행 흐름을 조율하고, Formatter는 필요한 변환을 정의합니다. 구체적인 형식 이름에 따라 분기하거나 Renderer를 변경하지 않고도 다른 구현 클래스를 제공할 수 있습니다.

Swift는 프로토콜로 협력 객체의 계약을 표현합니다. any Formatter 값은 프로토콜을 준수하는 모든 구현을 담을 수 있으며, 제네릭 매개변수는 제네릭 API에서 특정 구체 형식을 유지합니다. 두 접근 방식 모두 구체 형식 이름을 확인하지 않고 위임할 수 있습니다.

Swift의 실존 타입은 이에 대응하는 프로토콜 기반 추상화를 제공합니다. 두 구현 모두 제공된 협력 객체를 호출해야 합니다. 송장 작업에서는 사용자 지정 정책도 기본 정책만큼 잘 작동해야 합니다. 계산을 하나로 하드 코딩하면 설계 계약이 깨집니다.

완성된 PHP 비교 프로그램:

<?php
declare(strict_types=1);
interface Formatter { public function format(string $text): string; }
class UpperFormatter implements Formatter {
    public function format(string $text): string { return strtoupper($text); }
}
class Renderer {
    public function __construct(private Formatter $formatter) {}
    public function render(string $text): string { return $this->formatter->format($text); }
}
echo (new Renderer(new UpperFormatter()))->render("notice"), "\n";

다음 파일에서 컴파일한 완성된 Swift 비교 프로그램:

Formatter.swift

protocol Formatter { func format(_ text: String) -> String }

UpperFormatter.swift

struct UpperFormatter: Formatter { func format(_ text: String) -> String { text.uppercased() } }

Renderer.swift

struct Renderer {
    let formatter: any Formatter
    func render(_ text: String) -> String { formatter.format(text) }
}

main.swift

print(Renderer(formatter: UpperFormatter()).render("notice"))
challenge icon

챌린지

쉬움

Policy 프로토콜을 charge(for units: Int) -> Int와 함께 구현하세요. 요금이 rate와 units의 곱인 FlatPolicy(rate:)를 구현하세요. 임의의 Policy를 저장하고 total(units:)에서 해당 정책에 위임하는 Invoice(policy:)를 구현하세요. 사용자 지정 정책도 작동해야 합니다. 입력은 0부터 100까지의 rate와 0부터 100까지의 units입니다. 출력은 청구서 총액입니다.

필수 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") }
quiz icon실력 점검

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

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

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