从文档:
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);
这似乎不符合逻辑或一致,我找不到有关这个问题的任何文件.
这是设计吗?
解决方法
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
theErrorTypeprotocol. 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错误(可能会传播),无法处理
尝试.
你必须使用众所周知的技术可选绑定,可选链接,检查对等