Menu
CoddyTech

Port: Inventory Commands

Lesson 47 of 48 in Coddy's Swift for PHP Developers course.

challenge icon

Challenge

Medium

Port the PHP 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 PHP reference for the same input and output contract:

<?php
declare(strict_types=1);
final class Inventory {
    private array $stock = [];
    public function quantity(string $name): int { return $this->stock[$name] ?? 0; }
    public function add(string $name, int $count): bool {
        if ($count <= 0) return false;
        $this->stock[$name] = $this->quantity($name) + $count;
        return true;
    }
    public function take(string $name, int $count): bool {
        $available = $this->quantity($name);
        if ($count <= 0 || $count > $available) return false;
        $this->stock[$name] = $available - $count;
        return true;
    }
    public function report(): string {
        $sorted = $this->stock;
        ksort($sorted, SORT_STRING);
        $parts = [];
        foreach ($sorted as $name => $quantity) $parts[] = "$name:$quantity";
        return implode(" ", $parts);
    }
}
function solve(string $input): string {
    $tokens = preg_split('/\s+/', trim($input), -1, PREG_SPLIT_NO_EMPTY);
    $stock = new Inventory();
    $accepted = 0;
    for ($i = 0; $i < count($tokens); $i += 3) {
        $name = $tokens[$i + 1];
        $count = (int)$tokens[$i + 2];
        $ok = $tokens[$i] === "add" ? $stock->add($name, $count) : $stock->take($name, $count);
        if ($ok) $accepted++;
    }
    $report = $stock->report();
    return (string)$accepted . ($report === "" ? "" : " " . $report);
}
echo solve(stream_get_contents(STDIN)), "\n";

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 PHP Developers

Practice on your own: Swift playground