How does one trap arithmetic overflow errors in Swift?

前端 未结 2 633
长发绾君心
长发绾君心 2020-12-06 17:47

This one is probably easy. We know that the operator &+ does modular arithmetic on integers (wraps around), while the operator + causes an erro

相关标签:
2条回答
  • 2020-12-06 17:49

    Looks like this has become a non-static method in Swift 5, addingReportingOverflow(_:).

    So for example,

    UInt8.max.addingReportingOverflow(1)
    

    will return (partialValue: 0, overflow: true) See more on the Int manual page

    And of course the normal arithmetic operators that start with & to allow overflow without returning overflow reports,

    UInt8.max &+ 1
    

    would return 0 as a UInt8

    0 讨论(0)
  • 2020-12-06 17:55

    Distinguish between an exception and a runtime error. An exception is thrown and can be caught. A runtime error stops your program dead in its tracks. Adding and getting an overflow is a runtime error, plain and simple. There is nothing to catch.

    The point of an operator like &+ is that it doesn't error and it doesn't tell you there was a problem. That is the whole point.

    If you think you might overflow, and you want to know whether you did, use static methods like addWithOverflow. It returns a tuple consisting of the result and a Bool stating whether there was an overflow.

    var x: Int8 = 100
    let result = x &+ x // -56
    
    x = 100
    let result2 = Int8.addWithOverflow(x,x) // (-56, true)
    
    0 讨论(0)
提交回复
热议问题