他们两个看起来都一样。在哪个上下文中我们应该使用一个呢?
因此,例如,您可以对一些具有明显结果(在一定范围内)的计算放置一个断言,以快速查找是否有错误。但是你不会想要这样做,因为超越界的结果可能是有效的,并不重要,所以不应该崩溃你的应用程序(假设你只是使用它来显示进度条的进度)。
另一方面,在获取元素时检查数组上的下标是否有效是前提条件。当要求无效下标时,数组对象没有合理的下一个操作,因为它必须返回非可选值。
文档的完整文本(尝试选项 – 点击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): ifcondition
evaluates to false,stop program
execution in a debuggable state after printingmessage
.In -O builds (the default for Xcode’s Release configuration):
ifcondition
evaluates to false,stop program execution.In -Ounchecked builds,
condition
is not evaluated,but the
optimizer may assume that it would evaluate totrue
. 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; seeprecondition
.
In playgrounds and -Onone builds (the default for Xcode’s Debug
configuration): ifcondition
evaluates to false,stop program
execution in a debuggable state after printingmessage
.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 totrue
. Failure to satisfy that assumption in -Ounchecked builds is a serIoUs programming error.