Skip to content
Tutorials Center
My learning

Topics

Lesson 136 of 146 ยท Projects

Project: Inventory and Reports

Build an inventory system in Swift that imports CSV data, groups and sorts with dictionaries, prints aligned report tables and exports JSON with Codable. Full program, runs in your browser.

Most business software is, at heart, data in, reports out. A shop has a list of products. Somebody asks which categories hold the most stock value, which items must be reordered, and who the main suppliers are. Answering those questions is a matter of grouping, summing and sorting, then presenting the result as a readable table. Swift's standard library is very good at this, and this project is the best way to practice it.

You will build a complete inventory tool: it imports product data from CSV text and reports every bad row instead of crashing, stores products in a dictionary keyed by SKU, supports shipping and receiving goods, prints aligned report tables, and exports and re-imports JSON with Codable. Along the way you use dictionaries and dictionary patterns, higher-order functions, string formatting and Codable.

What we are building

The input is plain text, as it would come from a spreadsheet export:

TEXT
sku,name,category,price,quantity,reorder,supplier
LMP-100,Desk lamp,Lighting,24.99,40,15,Brightworks

The reports we want:

Command What it shows
report categories Items, units and stock value per category, richest first
report low Products at or below their reorder level, with how many to order
report top N The N products holding the most value
report suppliers Products and value per supplier
find text Products whose name contains the text
ship SKU n / receive SKU n Change stock levels, with proper errors
export, roundtrip JSON output, and a check that decoding gives back the same data

As in the other projects, the logic returns values (arrays of strings), and only the main loop prints. A report function is then easy to test: call it, compare the lines.

Step 1: importing messy data

Real data is never clean. A good importer does not stop at the first problem: it reads every row, keeps the good ones and reports every bad one with its line number, so that the person fixing the file can do it in a single pass. We model the problems as an enum and parse one row at a time with a function that throws a typed error:

Swift Step 1: CSV import that reports every bad row

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Study how the importer is built, because the same shape fits any file format.

  • importProducts loops over the lines and, for each one, runs parseRow inside do/catch. A failure is recorded and the loop continues. Compare that with throwing from importProducts itself, which would stop at row three and hide four other mistakes.
  • The numbered lineNumber is index + 1 because arrays start at zero and spreadsheets at one. Skipping the header with where index > 0 keeps the numbers aligned with what the user sees in their editor.
  • seen.insert(sku).inserted is the idiom for duplicate detection: Set.insert returns a tuple whose inserted flag is false when the element was already there. One call both checks and records.
  • The nested helpers text and count are typed-throwing functions that capture fields and line. They keep parseRow readable: each field is one line.
  • Money is parsed to integer cents with a small hand-written function, because Double("24.99") followed by multiplication by 100 can produce 2498.9999999999995. Exact text-to-integer parsing has no rounding risk.

This CSV parser is deliberately simple: it does not understand quoted fields such as "Chair, ergonomic" that contain commas. Real CSV needs a small state machine (inside quotes or not). The text processing lesson has the tools to build one.

Step 2: dictionaries do the heavy lifting

A report is mostly a question of the form "for each X, compute Y". Swift's dictionaries answer it in a few lines. The key tools:

  • Dictionary(grouping: items, by: key) builds [Key: [Item]] in one pass.
  • mapValues transforms every value and keeps the keys.
  • reduce or reduce(into:) folds a collection into a total, and dict[key, default: 0] += 1 is the idiom for counting.
  • Sorting turns a dictionary into an ordered array. Dictionary order is random, so every report must sort before it prints.
Swift Step 2: grouping, summing and sorting with dictionaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The sorting trick in ranked is worth memorizing. Tuples compare element by element, left to right. Writing ($0.value, $1.sku) > ($1.value, $0.sku) swaps the second element between the two sides, so the first part sorts descending and the tie-breaker (the SKU) ascending. A tie-breaker also makes the sort result fully deterministic, which matters because sorted is not guaranteed to be stable for equal elements in every API; adding a unique second key removes any doubt.

Dictionary(uniqueKeysWithValues:) is the strict constructor. It trusts you that the keys are unique, and when they are not, the program stops:

Swift Duplicate keys in uniqueKeysWithValues (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The run ends with Fatal error: Duplicate values for key: 'LMP-100' and a crash, which is the right behavior for a violated assumption in code, and the wrong one for data that comes from a file. For external data, deduplicate first (as the importer's Set did) or use the version that takes a uniquingKeysWith closure and decide who wins.

Step 3: money and tables

Reports are read by people, so they need aligned columns and readable numbers. Two small tools do the job: a money function that prints cents as $1,234.50, and a Table type that measures the widest cell in each column and pads every cell to match, left-aligned for text and right-aligned for numbers.

Swift Step 3: money formatting and a table renderer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

money works on Int cents, so it can never print $0.1 + $0.2 = $0.30000000000000004. The thousands separator loop walks the digits from the right and inserts a comma every third position. (formatted(.currency(code:)) exists in Foundation too, but it depends on the locale data of the machine, which is not what you want in a report whose text you test.)

The Table type separates measuring from drawing: first it finds the widest cell per column, then line pads each cell. One generic table type now serves every report in the program, and adding a column to a report is a one-line change. The footer is optional and rendered under a second rule.

Step 4: the complete program

Now we assemble everything. Inventory owns the dictionary keyed by SKU, so shipping and receiving are O(1) lookups, and exposes the sorted array for the reports. Operations that can fail throw a typed InventoryError with human-readable text. Reports are free functions on [Product]: they take products, return lines, and know nothing about the dictionary. The export encodes with keyEncodingStrategy = .convertToSnakeCase so the Swift name priceCents becomes price_cents in the file, and roundtrip decodes the JSON again and checks that nothing was lost.

Swift Step 4: the complete inventory and reports program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The most interesting function is run. It switches on a tuple (verb, args.first), which allows patterns such as ("report", "categories") that match both values at once, ("find", _?) which means "the second value is non-nil, whatever it is", and ("ship", let sku?) which also binds the unwrapped value. That one switch replaces a ladder of if statements and nested optional checks. You met these patterns in the pattern matching lesson.

A few other details deserve attention:

  • inout lets run change the caller's inventory while keeping the function easy to call and to test. The call site shows the mutation with &inventory.
  • guard var product = bySKU[sku] copies the product out of the dictionary (value semantics), changes the copy, and writes it back. bySKU[sku]?.quantity += quantity does the same in one line through optional chaining, which is nicer when no checks are needed in between.
  • report top has no number in the script, so Int(...) ?? 5 supplies a default. That is how you handle an optional argument with a fallback.
  • Untyped errors at the edge. Inside the inventory, errors are typed. run mixes several sources (including JSONEncoder), so it uses plain throws and the loop prints whatever arrives. The library code stays precise and the application edge stays flexible, which is a good rule of thumb.

Extending the project

  • Quoted CSV fields. Teach the importer about "Chair, ergonomic". It only needs a flag that flips on each quote character.
  • A stock history. Make ship and receive append Movement values to an array, then add report movements. Reports from history are the natural next step.
  • Price changes with percentage. receive could track an average cost with a weighted mean: (old * oldQty + new * newQty) / total, in integer cents with explicit rounding.
  • Locale output. Replace money with FormatStyle.currency for user-facing screens, while keeping the fixed format for logs and tests.
  • A real data store. The dictionary keyed by SKU maps almost directly onto a database table. See working with JSON for the file format side.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the importer collect errors instead of throwing at the first bad row?

    Each row runs inside its own do/catch, so one bad row does not hide the others. Good importers report everything in a single pass.
  2. 2. What does Dictionary(grouping: products, by: \.category) return?

    grouping:by: buckets the elements by the key you compute and returns a dictionary of arrays, in one pass.
  3. 3. Why must every report sort a dictionary before printing it?

    Swift randomizes the iteration order of dictionaries per process. Sorting by a key gives reproducible reports.
  4. 4. What does the comparison ($0.value, $1.sku) > ($1.value, $0.sku) achieve?

    Tuples compare element by element. Swapping the second element between the sides reverses only the tie-breaker's direction.
  5. 5. Why are prices stored as integer cents?

    Cents add and multiply exactly. Double introduces rounding errors that show up in totals.

Summary

  • Import external data defensively: parse each row in its own do/catch, keep line numbers, collect every error, and detect duplicates with Set.insert(...).inserted.
  • Dictionary(grouping:by:), mapValues, reduce and dict[key, default:] express most reports in a few lines; sort before printing because dictionary order is random.
  • Use tuple comparison to sort by several keys, with a unique key last for deterministic order.
  • Keep money in integer cents and format it at the edge; build tables from one reusable Table type that measures first and pads second.
  • Codable with keyEncodingStrategy = .convertToSnakeCase produces conventional JSON, and a round-trip check proves that export and import agree.
  • Switching on a tuple of command and argument gives a compact, exhaustive command dispatcher.

Next: Project: A Text Adventure Engine