Port: Inventory Commands
Lesson 47 of 48 in Coddy's Swift for Rust Developers course.
Challenge
MediumPort the Rust 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 Rust reference for the same input and output contract:
use std::collections::BTreeMap;
use std::io::{self, Read};
#[derive(Default)]
struct Inventory { stock: BTreeMap<String, i64> }
impl Inventory {
fn quantity(&self, name: &str) -> i64 { self.stock.get(name).copied().unwrap_or(0) }
fn add(&mut self, name: &str, count: i64) -> bool {
if count <= 0 { return false; }
let next = self.quantity(name) + count;
self.stock.insert(name.to_owned(), next);
true
}
fn take(&mut self, name: &str, count: i64) -> bool {
let available = self.quantity(name);
if count <= 0 || count > available { return false; }
self.stock.insert(name.to_owned(), available - count);
true
}
fn report(&self) -> String {
self.stock.iter().map(|(name, count)| format!("{}:{}", name, count))
.collect::<Vec<_>>().join(" ")
}
}
fn solve(input: &str) -> String {
let tokens: Vec<&str> = input.split_whitespace().collect();
let mut stock = Inventory::default();
let mut accepted = 0;
for command in tokens.chunks_exact(3) {
let count: i64 = command[2].parse().unwrap();
let ok = if command[0] == "add" { stock.add(command[1], count) }
else { stock.take(command[1], count) };
if ok { accepted += 1; }
}
let report = stock.report();
if report.is_empty() { accepted.to_string() } else { format!("{} {}", accepted, report) }
}
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
println!("{}", solve(&input));
}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 Rust 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