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错误(可能会传播),无法处理
尝试.

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...