Menu
CoddyTech

정책을 통한 합성

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

Go의 컴포지션은 인터페이스 값을 구조체 안에 저장하는 경우가 많습니다. Swift도 마찬가지로 모든 프로토콜을 런타임에 적합한 타입 중에서 선택할 수 있는 존재 타입으로 저장할 수 있습니다. 두 추상화 모두 하나의 구체적인 표현을 요구하지 않고 동작을 노출합니다.

소스의 Notice는 Formatter에 위임하며 Swift의 Notice도 마찬가지입니다. 대신 제네릭 설계에서는 구체적인 포매터 타입을 매개변수로 유지할 수 있습니다. 공유와 복사는 저장된 적합 타입이 값인지 참조인지에 따라 여전히 달라집니다.

Go: 완성된 프로그램

formatter.go

package main
type Formatter interface { Format(string) string }

brackets.go

package main
type Brackets struct{}
func (Brackets) Format(text string) string { return "[" + text + "]" }

notice.go

package main
type Notice struct { Formatter Formatter }
func (notice Notice) Render(text string) string { return notice.Formatter.Format(text) }

main.go

package main
import (
    "fmt"
)

func main() {
notice := Notice{Formatter: Brackets{}}
    fmt.Println(notice.Render("ready"))
}

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"))

구현에서 정책 호출을 유지하세요. 이를 Brackets의 알려진 공식으로 대체하면 다른 유효한 서식 동작을 제공하는 호출자가 제대로 동작하지 않게 됩니다.

challenge icon

챌린지

쉬움

Policy 프로토콜과 charge(for units: Int) -> Int를 구현하세요. 요금이 요율에 단위를 곱한 값인 FlatPolicy(rate:)를 구현하세요. 임의의 Policy를 저장하고 해당 정책에 처리를 위임하는 total(units:)를 포함한 Invoice(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)!
// 공개 API 점검 시작
let apiOK = apiChecks(input)
// 공개 API 점검 종료
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz icon실력 점검

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

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

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