Recap - Inventory
Part of the Logic & Flow section of Coddy's Swift journey — lesson 17 of 56.
Challenge
MediumYou're tracking shop inventory. Read a single line of input: a comma-separated list of operations against an initially-empty [String: Int] called stock. Each operation is one of:
in:<item>:<qty>add quantity to the item (use the default-subscript pattern)out:<item>:<qty>subtract quantity. If the resulting quantity is0or negative, remove the key entirely.
After applying every op, print:
- One line per remaining item, sorted alphabetically, in the format
<item>: <qty> Total units: <n>across every remaining value
For input in:apple:5,in:bread:2,out:apple:3,in:apple:4,out:bread:5, the output is:
apple: 6
Total units: 6Try it yourself
let ops = readLine()!.components(separatedBy: ",")
var stock: [String: Int] = [:]
// TODO: parse each op as kind:item:qty; in adds, out subtracts;
// remove keys whose qty drops to <= 0; print sorted lines + total
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check3Dictionaries
Declaring DictionariesOptional LookupUpdating DictionariesIterating DictionariesGrouping ValuesRecap - Inventory