Kelly Heath Kelly Heath - 2 months ago 11
Swift Question

Expected declaration error at the do { line using Swift 3

I am receiving an expected declaration error at the do { line. I have tried researching this and read over the Apple developer information for Swift 3 on try/catch statements but have not been able to figure this out.

Here is the code:

class Calculator: ViewController {

var display = "0"
var numerator : Float?
var denominator : Float?
var total : Float?


enum divisionErrors: Error {
case inf
case nan
}

func divide(num: Float, by denum: Float) throws -> Float {
guard num != 0 else{throw divisionErrors.nan}
guard denum != 0 else{throw divisionErrors.inf}

let computedValue = num / denum
return computedValue
}

do {

catch divisionErrors.inf {print("Error")}
display = "0"

catch divisionErrors.nan {print("Error")}
display = "0"
}
}

Answer

Your main problem is that you're attempting to use a do statement in the body of a class, whereas it should only be in the body of a function. For the sake of the argument, I'll put this in the viewDidLoad method.

class Calculator: UIViewController {

    var display = "0"
    var numerator : Float?
    var denominator : Float?
    var total : Float?


    enum divisionErrors: Error {
        case inf
        case nan
    }

    func divide(num: Float, by denum: Float) throws -> Float {
        guard num != 0 else{throw divisionErrors.nan}
        guard denum != 0 else{throw divisionErrors.inf}

        let computedValue = num / denum
        return computedValue
    }

    override func viewDidLoad() {

        do {
            try total = divide(num: numerator!, by: denominator!)

        } catch divisionErrors.inf {
            print("Error")
            display = "0"
        } catch divisionErrors.nan {
            print("Error")
            display = "0"
        } catch {
            assert(false, "Other Error")
        }
    }
}

In other words, when you do something, you must also try to do something that could fail. Afterwards, you close the do with some catch statements on your errors. Like a switch statement, your catch cases must be exhaustive. You will have errors when trying to compile without that final catch rounding up the rest of the possible errors, as potential errors transcend the scope of your divisionErrors enum.

You might also want to error check numerator and denominator to be sure they exist. I just force unwrapped them for the sake of the exercise.