summaryrefslogtreecommitdiff
path: root/src/calculator.swift
blob: dfd4c4c334dc2bcf4323f03cfee0bd25ddff4be0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
enum InvalidOperatorError: Error {
    case operatorNotSupported
}

func calculate(operatorThing: String, number1: Float, number2: Float) throws -> Float {
    switch operatorThing {
    case "+":
        return number1 + number2
    case "-":
        return number1 - number2
    case "/":
        return number1 / number2
    case "*":
        return number1 * number2
    default:
       throw InvalidOperatorError.operatorNotSupported
    }
}


func main() {
    print("enter a number:")
    let number1 = Float(readLine()!)!
    print("enter an operator:")
    let operatorThing = readLine()!
    print("enter another number:")
    let number2 = Float(readLine()!)!
    
    do {
        let result = try calculate(operatorThing: operatorThing, number1: number1, number2: number2) 
        print(result)
    } catch InvalidOperatorError.operatorNotSupported {
        print("invalid operator!")
        return
    } catch {
        print("unexpected error!")
        return
    }
}

main()