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 正式开源!Swift 团队很高兴宣布 Swift 开始开源新篇章。自从苹果发布 Swfit 编程语言,就成为了...
快,快,快!动动您的小手,分享给更多朋友! 苹果去年推出了全新的编程语言Swift,试图让iOS开发更简单...
开发者(KaiFaX) 面向开发者、程序员的专业平台! 和今年年初承诺的一样,苹果贴出了Swift语言的源码,...
本文由@Chun发表于Chun Tips :http://chun.tips/blog/2014/12/11/shi-yong-swift-gou-jian-zi-ding-yi...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...