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

前端之家收集整理的这篇文章主要介绍了swift中“precondition”和“assert”之间的区别?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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.

猜你在找的Swift相关文章