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

ios – 迅速强制解包异常不传播,第1张

概述我已经遇到这种愚蠢的行为,在 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 for 我已经遇到这种愚蠢的行为,在 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错误(可能会传播),无法处理
尝试.

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

总结

以上是内存溢出为你收集整理的ios – 迅速强制解包异常不传播全部内容,希望文章能够帮你解决ios – 迅速强制解包异常不传播所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1113044.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存