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

swift中“precondition”和“assert”之间的区别?,第1张

概述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.

总结

以上是内存溢出为你收集整理的swift中“precondition”和“assert”之间的区别?全部内容,希望文章能够帮你解决swift中“precondition”和“assert”之间的区别?所遇到的程序开发问题。

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

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

原文地址: https://outofmemory.cn/web/1058989.html

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

发表评论

登录后才能评论

评论列表(0条)

保存