Recap - Safe Calculator
Part of the Logic & Flow section of Coddy's Swift journey — lesson 48 of 56.
Challenge
MediumBuild 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
aandbas integers, throwing.parseif either fails - Throws
.unknownOpwhenopisn't one of+,-,*,/ - Throws
.divideByZerowhenop == "/"andb == 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 successparse error,div by zero, orunknown opfor 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: 2Try 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
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check