Menu
Coddy logo textTech

Calculator With History

Part of the Logic & Flow section of Coddy's Swift journey — lesson 56 of 56.

challenge icon

Challenge

Medium

Build a calculator that processes a stream of expressions, tolerates errors, and reports a per-operator history at the end.

Read a single line of input: a comma-separated list of a:op:b expressions. Operators are +, -, *, /. Define an enum CalcError: Error with cases parse, divideByZero, unknownOp.

For each expression, in order:

  • Print = <n> on success
  • Print parse, divZero, or unknownOp for each error case

After the per-expression lines, print one line per operator that succeeded at least once, in the fixed order +, -, *, /:

<op>: count=<n> sum=<total>

count is how many times that operator succeeded; sum is the total of those successful results.

For input 3:+:5,10:/:0,7:*:2,9:%:2,12:-:4,8:+:2, the output is:

= 8
divZero
= 14
unknownOp
= 8
= 10
+: count=2 sum=18
-: count=1 sum=8
*: count=1 sum=14

Try it yourself

let exprs = readLine()!.components(separatedBy: ",")
let order = ["+", "-", "*", "/"]

// TODO: enum CalcError; func compute(...) throws -> Int;
// loop, do/try, print outcome; build per-op history;
// final report in fixed order, only ops that succeeded

All lessons in Logic & Flow