Composition Through a Policy
Lesson 38 of 48 in Coddy's Swift for Dart Developers course.
Dart mixins reuse implementation through a class declaration, while composition stores a collaborator and asks it to perform work. Swift composition often stores any Protocol so several conforming types can provide behavior. This is runtime polymorphism without inheriting implementation from the collaborator. When the collaborator is a struct, it follows value semantics; when it is a class, the stored reference can share state. A generic stored collaborator is another design when its concrete type should remain part of the enclosing type. The example delegates text decoration to a bracket style.
Complete Dart program. Each labelled block is a separate file.
Style.dart
abstract interface class Style { String wrap(String text); }BracketStyle.dart
import 'Style.dart';
class BracketStyle implements Style {
@override
String wrap(String text) => '[$text]';
}Caption.dart
import 'Style.dart';
class Caption {
final Style style;
Caption(this.style);
String render(String text) => style.wrap(text);
}main.dart
import 'Caption.dart';
import 'BracketStyle.dart';
void main() { print(Caption(BracketStyle()).render('photo')); }Complete Swift program. Each labelled block is a separate file.
Style.swift
import Foundation
protocol Style { func wrap(_ text: String) -> String }BracketStyle.swift
import Foundation
struct BracketStyle: Style {
func wrap(_ text: String) -> String { "[" + text + "]" }
}Caption.swift
import Foundation
struct Caption {
let style: any Style
func render(_ text: String) -> String { style.wrap(text) }
}main.swift
import Foundation
print(Caption(style: BracketStyle()).render("photo"))Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Dart Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog Merge8Designing Types
Inheritance and OverridesComposition Through a PolicyAccess Control and InvariantsEnums with Associated ValuesFailable InitializationRecap: Booking LedgerPractice on your own: Swift playground