Menu
CoddyTech

Composition Through a Policy

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

Java composition often stores an interface reference inside a service. Swift can store an existential value written any Protocol, allowing a runtime choice among conforming types. The stored value may be a class reference or a value-type conformer.

The examples inject a formatter into a notice service. The service delegates formatting without knowing the concrete implementation. A generic design could instead bind the formatter type as a parameter; the existential design deliberately permits one property to hold different conforming types.

Java: complete program

Formatter.java

public interface Formatter { String format(String text); }

Brackets.java

public class Brackets implements Formatter {
  public String format(String text) { return "[" + text + "]"; }
}

Notice.java

public class Notice {
  private final Formatter formatter;
  public Notice(Formatter formatter) { this.formatter = formatter; }
  public String render(String text) { return formatter.format(text); }
}

Main.java

import java.util.*;
import java.util.function.*;
public class Main {

  public static void main(String[] args) throws Exception {
    Notice notice = new Notice(new Brackets());
    System.out.println(notice.render("ready"));
  }
}

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

Do not test for one concrete formatter and replace the protocol call with its known formula. Doing so breaks callers that supply another conformer with different behavior.

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 Java Developers

Practice on your own: Swift playground