ポリシーによるコンポジション
Coddyの「Go開発者のためのSwift」コースのレッスン 38/48。
Goのコンポジションでは、インターフェース値を構造体の中に格納することがよくあります。Swiftでも同様に、任意のProtocolを存在型として格納し、実行時に適合する型の中から選択できます。どちらの抽象化も、具体的な表現を1つに限定せずに振る舞いを公開します。
Goの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の式に置き換えると、別の有効な書式設定動作を指定する呼び出し元で問題が発生します。
チャレンジ
簡単Policy プロトコルと charge(for units: Int) -> Int を実装してください。料金が rate と units の積となる FlatPolicy(rate:) を実装してください。任意の Policy を保持し、total(units:) でその Policy に処理を委譲する Invoice(policy:) を実装してください。独自のポリシーも動作する必要があります。入力は rate が 0 から 100、units が 0 から 100 です。出力は請求書の合計です。
必要な API と solve(_ input: String) -> String を実装してください。末尾に改行を付けずに出力テキストを返し、編集可能なコードでは出力しないでください。ロックされたドライバーは、追加の有効な入力で API を個別に確認してから、返されたテキストをちょうど 1 つの改行とともに出力します。すべての数値演算は 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") }
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Go開発者のためのSwiftのすべてのレッスン
自分で練習してみよう: Swiftプレイグラウンド