Menu
CoddyTech

Port: Inventory Commands

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

challenge icon

Challenge

Medium

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

extends SceneTree
class Inventory:
    var _stock: Dictionary = {}
    func quantity(name: String) -> int:
        return _stock.get(name, 0)
    func add(name: String, count: int) -> bool:
        if count <= 0:
            return false
        _stock[name] = quantity(name) + count
        return true
    func take(name: String, count: int) -> bool:
        var available = quantity(name)
        if count <= 0 or count > available:
            return false
        _stock[name] = available - count
        return true
    func report() -> String:
        var names = _stock.keys()
        names.sort()
        var rows: Array[String] = []
        for name in names:
            rows.append("%s:%d" % [name, _stock[name]])
        return " ".join(rows)
func read_tokens() -> Array[String]:
    var bytes = PackedByteArray()
    while true:
        var chunk = OS.read_buffer_from_stdin(4096)
        if chunk.is_empty():
            break
        bytes.append_array(chunk)
    var pattern = RegEx.new()
    pattern.compile("\\S+")
    var tokens: Array[String] = []
    for found in pattern.search_all(bytes.get_string_from_utf8()):
        tokens.append(found.get_string())
    return tokens
func _init():
    var tokens = read_tokens()
    var inventory = Inventory.new()
    var accepted = 0
    for index in range(0, tokens.size(), 3):
        var count = tokens[index + 2].to_int()
        var success: bool
        if tokens[index] == "add":
            success = inventory.add(tokens[index + 1], count)
        else:
            success = inventory.take(tokens[index + 1], count)
        if success:
            accepted += 1
    var report = inventory.report()
    print(str(accepted) + (" " + report if not report.is_empty() else ""))
    quit()

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

Practice on your own: Swift playground