Can you catch overflow?

Hi

 

I was wondering how to handle the odd case of overflow. Swift is pretty keen to catch setting an Int to -Int.min, which is instant overflow. So I tricked the compiler by doing this:

 

        var m = Int.min + 10
        for _ in 1 ... 10 {
            m -= 1
        }
        do {
            let n = -m
            print("Minus min =", n)
        } catch {
            print("Trying to do -Int.min", error)
        }

I first did it without the do catch, and it just crashed the app. But there is no Error that gets caught by the do … catch syntax.

Short of testing if m != Int.min every time you use the negative operator, is there a way to catch these gracefully?

Powered by WPeMatico

About

You may also like...

Comments are closed.