Port: Inventory Commands
Lesson 47 of 48 in Coddy's Swift for C Developers course.
Challenge
MediumPort the C 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 C Inventory stores bounded entries inline and updates the original through a pointer. It sorts a temporary array for its report, leaving stored state unchanged. Preserve the required Swift reference-type API and all state after rejected commands.
Complete C reference program. Compile main.c with inventory.h beside it; the header supplies the implementation used by the sole entry point. The implementation is intentionally complete for this final port.
inventory.h
#ifndef INVENTORY_H
#define INVENTORY_H
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { char name[11]; int quantity; } Item;
typedef struct { Item items[40]; int size; } Inventory;
static int inventory_find(const Inventory *inventory, const char *name) {
for (int i = 0; i < inventory->size; ++i)
if (strcmp(inventory->items[i].name, name) == 0) return i;
return -1;
}
static int inventory_quantity(const Inventory *inventory, const char *name) {
int index = inventory_find(inventory, name);
return index < 0 ? 0 : inventory->items[index].quantity;
}
static bool inventory_add(Inventory *inventory, const char *name, int count) {
if (count <= 0) return false;
int index = inventory_find(inventory, name);
if (index < 0) {
index = inventory->size++;
strcpy(inventory->items[index].name, name);
inventory->items[index].quantity = 0;
}
inventory->items[index].quantity += count;
return true;
}
static bool inventory_take(Inventory *inventory, const char *name, int count) {
int available = inventory_quantity(inventory, name);
if (count <= 0 || count > available) return false;
inventory->items[inventory_find(inventory, name)].quantity = available - count;
return true;
}
static int item_compare(const void *left, const void *right) {
return strcmp(((const Item *)left)->name, ((const Item *)right)->name);
}
static void inventory_report(const Inventory *inventory, char output[1024]) {
Item sorted[40];
memcpy(sorted, inventory->items, (size_t)inventory->size * sizeof(Item));
qsort(sorted, (size_t)inventory->size, sizeof(Item), item_compare);
size_t used = 0;
output[0] = '\0';
for (int i = 0; i < inventory->size; ++i)
used += (size_t)snprintf(output + used, 1024 - used, "%s%s:%d", i ? " " : "", sorted[i].name, sorted[i].quantity);
}
#endif
main.c
#include "inventory.h"
int main(void) {
Inventory inventory = {0};
char command[5], name[11], report[1024];
int count, accepted = 0;
while (scanf("%4s %10s %d", command, name, &count) == 3) {
bool ok = strcmp(command, "add") == 0
? inventory_add(&inventory, name, count)
: inventory_take(&inventory, name, count);
if (ok) ++accepted;
}
inventory_report(&inventory, report);
printf("%d%s%s\n", accepted, report[0] ? " " : "", report);
return 0;
}
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 C 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