加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift中“precondition”和“assert”之间的区别?

发布时间:2020-12-14 06:07:28 所属栏目:百科 来源:网络整理
导读:Swift中precondition(condition:Bool,message:String)和assert(condition:Bool,message:String)之间有什么区别? 他们两个看起来都一样。在哪个上下文中我们应该使用一个呢? 断言是在测试期间的理性检查,而前提条件是防御的事情,如果发生,意味着你
Swift中precondition(condition:Bool,message:String)和assert(condition:Bool,message:String)之间有什么区别?

他们两个看起来都一样。在哪个上下文中我们应该使用一个呢?

断言是在测试期间的理性检查,而前提条件是防御的事情,如果发生,意味着你的程序只是不能合理地进行。

因此,例如,您可以对一些具有明显结果(在一定范围内)的计算放置一个断言,以快速查找是否有错误。但是你不会想要这样做,因为超越界的结果可能是有效的,并不重要,所以不应该崩溃你的应用程序(假设你只是使用它来显示进度条的进度)。

另一方面,在获取元素时检查数组上的下标是否有效是前提条件。当要求无效下标时,数组对象没有合理的下一个操作,因为它必须返回非可选值。

文档的完整文本(尝试选项 – 点击Xcode中的assert和precondition):

前提

Check a necessary condition for making forward progress.

Use this function to detect conditions that must prevent the
program from proceeding even in shipping code.

  • In playgrounds and -Onone builds (the default for Xcode’s Debug
    configuration): if condition evaluates to false,stop program
    execution in a debuggable state after printing message.

  • In -O builds (the default for Xcode’s Release configuration):
    if condition evaluates to false,stop program execution.

  • In -Ounchecked builds,condition is not evaluated,but the
    optimizer may assume that it would evaluate to true. Failure
    to satisfy that assumption in -Ounchecked builds is a serious
    programming error.

断言

Traditional C-style assert with an optional message.

Use this function for internal sanity checks that are active
during testing but do not impact performance of shipping code.
To check for invalid usage in Release builds; see precondition.

  • In playgrounds and -Onone builds (the default for Xcode’s Debug
    configuration): if condition evaluates to false,stop program
    execution in a debuggable state after printing message.

  • In -O builds (the default for Xcode’s Release configuration),
    condition is not evaluated,and there are no effects.

  • In -Ounchecked builds,but the
    optimizer may assume that it would evaluate to true. Failure to satisfy that assumption in -Ounchecked builds is a serious programming error.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读