Parcel Pricing
Lesson 46 of 48 in Coddy's Swift for C# Developers course.
Challenge
MediumKeep all earlier behavior. Complete quote(using policy: any PricePolicy) -> Int: sum the supplied policy cost separately for every remaining parcel. UnitPrice(rate:) costs weight times rate. Do not replace a custom policy with a fixed formula. All four stages use the same files and driver. Parcel(id:weight:) is a value type, and ParcelDesk() is a reference type. Input starts with this stage number 4 followed by 0 through 30 ID/weight pairs. IDs are 1 through 10 lowercase ASCII letters, weights 0 through 100. Ignore duplicate IDs. Output quote using a unit price of 3. Future-stage methods remain placeholders until their named stage.
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 Parcel.swift, PricePolicy.swift, UnitPrice.swift, ParcelDesk.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 ProbePrice: PricePolicy { func cost(weight: Int) -> Int { weight + 11 } }
let p = input.split(whereSeparator: { $0.isWhitespace }); let stage = Int(p[0])!
let d = ParcelDesk()
guard d.add(Parcel(id: "p", weight: 7)), !d.add(Parcel(id: "p", weight: 9)), d.add(Parcel(id: "q", weight: 2)), d.count == 2 else { return false }
if stage >= 2 { guard d.totalWeight == 9 else { return false } }
if stage >= 3 { guard d.dispatch("missing") == nil && d.count == 2 else { return false }; guard d.dispatch("p")?.weight == 7 && d.count == 1 && d.totalWeight == 2 && d.dispatch("p") == nil else { return false } }
if stage >= 4 { guard UnitPrice(rate: 5).cost(weight: 4) == 20 && d.quote(using: ProbePrice()) == 13 && d.quote(using: UnitPrice(rate: 4)) == 8 else { return false } }
return true
}
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") }
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 RulesPractice on your own: Swift playground