Menu
CoddyTech

Port: Inventory Commands

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

challenge icon

Challenge

Medium

Port the Go 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 Go Inventory is accessed through a pointer and owns a map whose keys are sorted explicitly for reporting. Copying a Go map value would still share the underlying entries. Preserve the required Swift reference-type API and all state after rejected commands.

Complete Go reference program. Compile these package main files together; main.go contains the sole main function. The implementation is intentionally complete for this final port.

inventory.go

package main
import ("sort"; "strconv"; "strings")
type Inventory struct { stock map[string]int }
func NewInventory() *Inventory { return &Inventory{stock: make(map[string]int)} }
func (inventory *Inventory) Quantity(name string) int { return inventory.stock[name] }
func (inventory *Inventory) Add(name string, count int) bool {
    if count <= 0 { return false }
    inventory.stock[name] = inventory.Quantity(name) + count
    return true
}
func (inventory *Inventory) Take(name string, count int) bool {
    available := inventory.Quantity(name)
    if count <= 0 || count > available { return false }
    inventory.stock[name] = available - count
    return true
}
func (inventory *Inventory) Report() string {
    names := make([]string, 0, len(inventory.stock))
    for name := range inventory.stock { names = append(names, name) }
    sort.Strings(names)
    rows := make([]string, 0, len(names))
    for _, name := range names { rows = append(rows, name+":"+strconv.Itoa(inventory.stock[name])) }
    return strings.Join(rows, " ")
}

main.go

package main
import ("bufio"; "fmt"; "os")
func main() {
    input := bufio.NewReader(os.Stdin)
    inventory := NewInventory()
    accepted := 0
    for {
        var command, name string
        var count int
        if _, err := fmt.Fscan(input, &command, &name, &count); err != nil { break }
        var ok bool
        if command == "add" { ok = inventory.Add(name, count) } else { ok = inventory.Take(name, count) }
        if ok { accepted++ }
    }
    report := inventory.Report()
    fmt.Print(accepted)
    if report != "" { fmt.Print(" ", report) }
    fmt.Println()
}

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

Practice on your own: Swift playground