Menu
CoddyTech

Port: Inventory Commands

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

challenge icon

Challenge

Medium

Port the Dart 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 Dart Inventory is a mutable class with shared identity. Preserve that behavior with the required Swift class. Dart named count arguments become the labels specified by the Swift API.

Complete Dart program. Each labelled block is a separate file.

Inventory.dart

class Inventory {
  final Map<String, int> _stock = {};
  int quantity(String name) => _stock[name] ?? 0;
  bool add(String name, {required int count}) {
    if (count <= 0) return false;
    _stock[name] = quantity(name) + count;
    return true;
  }
  bool take(String name, {required int count}) {
    final available = quantity(name);
    if (count <= 0 || count > available) return false;
    _stock[name] = available - count;
    return true;
  }
  String report() {
    final names = _stock.keys.toList()..sort();
    return names.map((name) => '$name:${_stock[name]}').join(' ');
  }
}

Functions.dart

import 'Inventory.dart';
String solve(String input) {
  final trimmed = input.trim();
  final words = trimmed.isEmpty ? <String>[] : trimmed.split(RegExp(r'\s+'));
  final inventory = Inventory();
  var accepted = 0;
  for (var index = 0; index < words.length; index += 3) {
    final name = words[index + 1];
    final count = int.parse(words[index + 2]);
    final ok = words[index] == 'add'
        ? inventory.add(name, count: count)
        : inventory.take(name, count: count);
    if (ok) accepted += 1;
  }
  final summary = inventory.report();
  return summary.isEmpty ? '$accepted' : '$accepted $summary';
}

main.dart

import 'dart:io';
import 'Functions.dart';
void main() {
  final input = StringBuffer();
  String? line;
  while ((line = stdin.readLineSync()) != null) {
    input.writeln(line);
  }
  print(solve(input.toString()));
}

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

Practice on your own: Swift playground