How does one trap arithmetic overflow errors in Swift?

前端 未结 2 636
长发绾君心
长发绾君心 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

提交回复
热议问题