Port: Inventory Commands
Lesson 47 of 48 in Coddy's Swift for Python Developers course.
Challenge
MediumPort the Python reference into Swift. Implement Inventory() with add(_ name: String, count: Int) -> Bool, take(_ name: String, count: Int) -> Bool, quantity(of name: String) -> Int, and report() -> String. Add accepts only positive counts. Take accepts only positive counts at most current stock. Rejections preserve all state; unknown quantities are zero. Successful takes retain zero-stock entries. Report all stored names ascending as name:quantity separated by spaces. Input contains 0 through 40 command triples: add name count or take name count. Names are lowercase ASCII words up to 10 letters, counts -10 through 100. Output successful command count, followed by a space and report only when nonempty.
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.
Complete Python reference for the same input and output contract:
import sys
class Inventory:
def __init__(self):
self._stock = {}
def add(self, name, count):
if count <= 0:
return False
self._stock[name] = self.quantity(name) + count
return True
def take(self, name, count):
available = self.quantity(name)
if count <= 0 or count > available:
return False
self._stock[name] = available - count
return True
def quantity(self, name):
return self._stock.get(name, 0)
def report(self):
return " ".join(f"{name}:{self._stock[name]}" for name in sorted(self._stock))
def solve(text):
inventory = Inventory()
tokens = text.split()
accepted = 0
for offset in range(0, len(tokens), 3):
command, name, count_text = tokens[offset:offset + 3]
count = int(count_text)
if command == "add":
success = inventory.add(name, count)
else:
success = inventory.take(name, count)
accepted += int(success)
report = inventory.report()
return str(accepted) + (" " + report if report else "")
if __name__ == "__main__":
print(solve(sys.stdin.read()))Your code goes in Inventory.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 {
let x = Inventory(); guard x.quantity(of: "missing") == 0 && !x.take("missing", count: 1) && x.report().isEmpty else { return false }; guard x.add("oak", count: 4) && !x.take("oak", count: 5) && !x.add("oak", count: 0) && x.quantity(of: "oak") == 4 else { return false }; return x.take("oak", count: 4) && x.report() == "oak:0" && !x.take("oak", count: -1) && Inventory().report().isEmpty
}
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
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