Composition Through a Policy
Lesson 38 of 48 in Coddy's Swift for C Developers course.
C composition can store a function pointer or callback interface inside another struct. Swift can store an existential any Protocol value to choose behavior at runtime among conforming types. That stored conformer may be a value type or a class reference.
The notice delegates to the supplied formatter in both examples. C explicitly passes an output buffer and its capacity; Swift returns a managed String. A generic Swift design could bind the policy type as a parameter instead, while this existential allows runtime choices behind one interface.
C: complete program
formatter.h
#ifndef FORMATTER_H
#define FORMATTER_H
#include <stddef.h>
typedef struct { void (*format)(const char *, char *, size_t); } Formatter;
#endif
brackets.h
#ifndef BRACKETS_H
#define BRACKETS_H
#include <stdio.h>
#include "formatter.h"
static void brackets(const char *text, char *output, size_t capacity) { snprintf(output, capacity, "[%s]", text); }
#endif
notice.h
#ifndef NOTICE_H
#define NOTICE_H
#include "formatter.h"
typedef struct { Formatter formatter; } Notice;
static void notice_render(const Notice *notice, const char *text, char *output, size_t capacity) {
notice->formatter.format(text, output, capacity);
}
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "brackets.h"
#include "notice.h"
int main(void) {
Notice notice = {{brackets}};
char output[32];
notice_render(¬ice, "ready", output, sizeof output);
puts(output);
return 0;
}
Swift: complete program
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"))Keep the callback or protocol call intact. Replacing it with the known formula of one sample implementation breaks callers that provide another valid policy.
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 C 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