ios – 迅速强制解包异常不传播

前端之家收集整理的这篇文章主要介绍了ios – 迅速强制解包异常不传播前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经遇到这种愚蠢的行为,在 swift中,强制解包可选不传播.

从文档:

Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

复制:

func foo(bar:String?) throws{
    print(bar!);
}

try foo(nil);

这似乎不符合逻辑或一致,我找不到有关这个问题的任何文件.

这是设计吗?

解决方法

documentation

Error Handling

Error handling is the process of responding to and recovering from
error conditions in your program. Swift provides first-class support
for throwing,catching,propagating,and manipulating recoverable
errors at runtime.

Representing and Throwing Errors

In Swift,errors are represented by values of types that conform to
the ErrorType protocol. This empty protocol indicates that a type can
be used for error handling.

(注意:在Swift 3中,ErrorType已重命名为Error)

所以使用try / catch可以处理抛出的Swift错误(符合ErrorType协议的类型的值).
这与运行时错误和运行时异常完全无关
(也与基金会图书馆的NSException无关).

请注意,关于错误处理的Swift文档甚至不使用
字“异常”,唯一的例外(!)在(强调我的)在:

NOTE

Error handling in Swift resembles exception handling in other
languages,with the use of the try,catch and throw keywords. Unlike
exception handling in many languages—including Objective-C—error
handling in Swift does not involve unwinding the call stack,a process
that can be computationally expensive. As such,the performance
characteristics of a throw statement are comparable to those of a
return statement.

包括任何选项的解开不会抛出
Swift错误(可能会传播),无法处理
尝试.

你必须使用众所周知的技术可选绑定,可选链接,检查对等

原文链接:https://www.f2er.com/iOS/337353.html

猜你在找的iOS相关文章