Menu
CoddyTech

Parcel Weight Report

Lesson 44 of 48 in Coddy's Swift for Python Developers course.

challenge icon

Challenge

Medium

Keep intake behavior. Complete computed totalWeight: Int, the sum of stored parcel weights, including zero for an empty desk. 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 2 followed by 0 through 30 ID/weight pairs. IDs are 1 through 10 lowercase ASCII letters, weights 0 through 100. Ignore duplicate IDs. Output total stored weight. 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 Python Developers

Practice on your own: Swift playground