Menu
CoddyTech

Composition Through a Policy

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

R can compose behavior by storing a collaborator list with a function element. Force evaluates the factory argument before the returned closure uses it later, making the captured collaborator choice explicit under lazy evaluation. Its format member is a runtime convention rather than a protocol declaration.

Swift expresses the collaborator contract with a protocol. An any Formatter value can hold any conforming implementation, while a generic parameter preserves a particular concrete type through a generic API. Both approaches allow delegation without checking the concrete type name.

The Swift renderer stores a protocol existential and delegates through its requirement. Both designs permit replacement policies. In the invoice task, call the supplied policy rather than duplicating one known formula, so custom policies receive the same authority over their result.

Complete R comparison program:

upper_formatter <- list(format = function(text) toupper(text))
make_renderer <- function(formatter) {
  force(formatter)
  list(render = function(text) formatter$format(text))
}
renderer <- make_renderer(upper_formatter)
cat(renderer$render("notice"), "\n", sep = "")

Complete Swift comparison program, compiled from these files:

Formatter.swift

protocol Formatter { func format(_ text: String) -> String }

UpperFormatter.swift

struct UpperFormatter: Formatter { func format(_ text: String) -> String { text.uppercased() } }

Renderer.swift

struct Renderer {
    let formatter: any Formatter
    func render(_ text: String) -> String { formatter.format(text) }
}

main.swift

print(Renderer(formatter: UpperFormatter()).render("notice"))
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 R Developers

Practice on your own: Swift playground