Menu
CoddyTech

Composition Through a Policy

Lesson 38 of 48 in Coddy's Swift for C++ Developers course.

C++ composition can retain a reference to an abstract policy, a smart pointer owner or a concrete template parameter, each with different lifetime and dispatch rules. This source borrows a Decorator that stays alive throughout use. Swift stores any Decorator as an existential, allowing either value-type or class conformers. The surrounding Display delegates instead of inheriting one particular implementation. Keep the actual policy call rather than substituting a formula known from the sample Brackets type; callers may provide different valid behavior. A small interface makes that substitution testable and avoids exposing implementation-specific fields.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
struct Decorator { virtual std::string wrap(const std::string &) const = 0; virtual ~Decorator() = default; };
struct Brackets : Decorator { std::string wrap(const std::string &text) const override { return "[" + text + "]"; } };
struct Display { const Decorator &decorator; std::string render(const std::string &text) const { return decorator.wrap(text); } };

int main() {
Brackets brackets;
    Display display{brackets};
    std::cout << display.render("news") << '\n';
}

Swift

Complete program file: Decorator.swift.

protocol Decorator { func wrap(_ text: String) -> String }

Complete program file: Brackets.swift.

struct Brackets: Decorator { func wrap(_ text: String) -> String { "[" + text + "]" } }

Complete program file: Display.swift.

struct Display {
    let decorator: any Decorator
    func render(_ text: String) -> String { decorator.wrap(text) }
}

Complete program file: main.swift.

let display = Display(decorator: Brackets())
print(display.render("news"))
challenge icon

Challenge

Easy

Implement Policy protocol with charge(for units: Int) -> Int. Implement FlatPolicy(rate:), whose charge is rate times units. Implement Invoice(policy:) storing any Policy, with total(units:) delegating to that policy. Custom policies must work. Input is rate 0 through 100 and units 0 through 100. Output invoice total.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Policy.swift, FlatPolicy.swift, Invoice.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

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)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for C++ Developers

Practice on your own: Swift playground