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?

Replies

There is the m.subtractingReportingOverflow func in Swift that could help : it returns a tuple, with the value and an oberflow status.

h ttps://developer.apple.com/documentation/swift/uint64/2883770-subtractingreportingoverflow


var m = Int.min + 10
for _ in 1 ... 12 {
    let result = m.subtractingReportingOverflow(1) //Int.subtractWithOverflow(m, 1)
    print(result)
    if result.overflow { print("overflow error") ; break }
    m -= 1
}


you get :

(partialValue: -9223372036854775799, overflow: false)

(partialValue: -9223372036854775800, overflow: false)

(partialValue: -9223372036854775801, overflow: false)

(partialValue: -9223372036854775802, overflow: false)

(partialValue: -9223372036854775803, overflow: false)

(partialValue: -9223372036854775804, overflow: false)

(partialValue: -9223372036854775805, overflow: false)

(partialValue: -9223372036854775806, overflow: false)

(partialValue: -9223372036854775807, overflow: false)

(partialValue: -9223372036854775808, overflow: false)

(partialValue: 9223372036854775807, overflow: true)

overflow error


Noote that min - 1 -> max : wraps around " infinity "