Port: Inventory Commands
Lesson 47 of 48 in Coddy's Swift for Java Developers course.
Challenge
MediumPort the Java 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.
The Java Inventory has reference semantics and uses TreeMap to order its report. Its final map binding does not make the entries immutable. Preserve the required Swift reference-type API and all state after rejected commands.
Complete Java 17 reference program. Compile these files together; Main.java is the only entry point. The implementation is intentionally complete for this final port.
Inventory.java
import java.util.Map;
import java.util.TreeMap;
import java.util.StringJoiner;
public final class Inventory {
private final Map<String, Integer> stock = new TreeMap<>();
public boolean add(String name, int count) {
if (count <= 0) return false;
stock.put(name, quantity(name) + count);
return true;
}
public boolean take(String name, int count) {
int available = quantity(name);
if (count <= 0 || count > available) return false;
stock.put(name, available - count);
return true;
}
public int quantity(String name) { return stock.getOrDefault(name, 0); }
public String report() {
StringJoiner result = new StringJoiner(" ");
stock.forEach((name, count) -> result.add(name + ":" + count));
return result.toString();
}
}Main.java
import java.util.Scanner;
public final class Main {
public static void main(String[] args) {
Inventory inventory = new Inventory();
int accepted = 0;
try (Scanner input = new Scanner(System.in)) {
while (input.hasNext()) {
String command = input.next();
String name = input.next();
int count = input.nextInt();
boolean ok = command.equals("add")
? inventory.add(name, count) : inventory.take(name, count);
if (ok) accepted++;
}
}
String report = inventory.report();
System.out.println(accepted + (report.isEmpty() ? "" : " " + report));
}
}Implement the Swift APIs in Inventory.swift, Functions.swift. Keep the supplied main.swift driver.
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 Java 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