Menu
Coddy logo textTech

Recap - Inventory Item

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 11 of 57.

challenge icon

Challenge

Medium

Complete the struct StockItem with the properties name and quantity. Add the mutating methods receive(_:) (adds) and ship(_:) (subtracts only when enough is in stock, returning whether it did), and a non-mutating label() that returns tea: 12 or tea: out of stock for quantity 0.

Then complete process(start:commands:): it creates the item, keeps a copy of it called opening before the first command, applies the commands, and returns one line per refused shipment (cannot ship 5), then now followed by the item's label and was followed by the label of opening.

The supplied code reads the item as name,quantity and the commands +n or -n, and prints each returned line.

Your code goes in StockItem.swift and Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let p = input[0].split(separator: ",").map(String.init)
let item = StockItem(name: p[0], quantity: Int(p[1])!)
for line in process(start: item, commands: Array(input.dropFirst())) { print(line) }

All lessons in Object Oriented Programming

Practice on your own: Swift playground