Ray*_*oal 8 error-handling integer-overflow swift
这个可能很容易.我们知道运算符&+对整数(环绕)进行模运算,而运算符+会导致错误.
$ swift
1> var x: Int8 = 100
x: Int8 = 100
2> x &+ x
$R0: Int8 = -56
3> x + x
Execution interrupted. Enter Swift code to recover and continue.
Run Code Online (Sandbox Code Playgroud)
这有什么错误?我无法抓住它,我无法将其转为可选:
4> do {try x + x} catch {print("got it")}
Execution interrupted. Enter Swift code to recover and continue.
5> try? x + x
Execution interrupted. Enter Swift code to recover and continue.
Run Code Online (Sandbox Code Playgroud)
我很确定这种错误是这个StackOverflow问题(除零)的错误,但我不知道是否可以捕获这种错误.我错过了什么简单的事情?可以被困吗?如果是这样,怎么样?
mat*_*att 11
区分异常和运行时错误.抛出异常并可以捕获.运行时错误会使程序停止运行.添加和获取溢出是一个运行时错误,简单明了.没什么好抓的.
操作员的意思&+是它没有错误,也没有告诉你有问题.这就是重点.
如果您认为自己可能会溢出,并且想知道自己是否会这样做,请使用静态方法addWithOverflow.它返回一个由结果组成的元组和一个Bool,说明是否有溢出.
var x: Int8 = 100
let result = x &+ x // -56
x = 100
let result2 = Int8.addWithOverflow(x,x) // (-56, true)
Run Code Online (Sandbox Code Playgroud)
看起来这已经成为 Swift 5 中的非静态方法,addingReportingOverflow(_:).
例如,
UInt8.max.addingReportingOverflow(1)
Run Code Online (Sandbox Code Playgroud)
将返回在手册页(partialValue: 0, overflow: true)上查看更多信息Int
当然还有&以允许溢出而不返回溢出报告开头的普通算术运算符,
UInt8.max &+ 1
Run Code Online (Sandbox Code Playgroud)
将返回0作为UInt8
| 归档时间: |
|
| 查看次数: |
1534 次 |
| 最近记录: |