Menu
Coddy logo textTech

Recap - Safe Calculator

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

challenge icon

Challenge

Medium

Build a tiny calculator that's safe against bad input.

Define CalcError: Error with cases: parse, divideByZero, unknownOp.

Define a throwing function compute(_ a: String, _ op: String, _ b: String) throws -> Int that:

  • Parses a and b as integers, throwing .parse if either fails
  • Throws .unknownOp when op isn't one of +, -, *, /
  • Throws .divideByZero when op == "/" and b == 0
  • Otherwise returns the integer result

Read a single line of input: a comma-separated list of a:op:b expressions. Process each in order with a do/catch. Print one line per expression:

  • = <n> on success
  • parse error, div by zero, or unknown op for each error case

After the per-expression lines, print one summary line: OK: <n> with the count of expressions that succeeded.

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

= 8
div by zero
parse error
unknown op
= 8
OK: 2

Try it yourself

let exprs = readLine()!.components(separatedBy: ",")

// TODO: enum CalcError; func compute(...) throws -> Int;
// loop, do/try, print outcome per expr; finally print 'OK: <n>'

All lessons in Logic & Flow