Swift -Ounchecked和断言 [英] Swift -Ounchecked and Assertions
问题描述
在Swift中,ENABLE_NS_ASSERTIONS
被忽略,并且断言是打开还是关闭取决于SWIFT_OPTIMIZATION_LEVEL
,
In Swift, ENABLE_NS_ASSERTIONS
is ignored, and whether assertions are on or off is dependent of SWIFT_OPTIMIZATION_LEVEL
, see here for more information.
-
assert()
对-Onone
处于活动状态 -
assertionFailure()
在以下时间处于活动状态-Onone
-
precondition()
对于-Onone
和-O
是活动的
-
preconditionFailure()
对于-Onone
,-O
和-Ounchecked
是活动的
-
fatalError()
对于-Onone
,-O
和-Ounchecked
是活动的
assert()
is active for-Onone
assertionFailure()
is active for-Onone
precondition()
is active for-Onone
and-O
preconditionFailure()
is active for-Onone
,-O
and-Ounchecked
fatalError()
is active for-Onone
,-O
and-Ounchecked
调试和Beta版构建应具有启用的断言,发布版本应具有已禁用的断言.
Debug and Beta Builds should have assertions enabled, Release Builds should have assertions disabled.
我可以通过precondition
方法在Swift中编写所有断言,并使用-Ounchecked
标志编译Release版本,使用-O
标志编译beta版本.
I could write all my assertions in Swift via the precondition
method and compile Release builds with the -Ounchecked
flag, beta builds with the -O
flag.
iOS版本中的默认版本为-O
.有什么建议不要使用-Ounchecked
进行发行版本?这可能会导致其他哪些不良副作用?
The default in iOS for Release builds is -O
. Is there anything advised against using -Ounchecked
for release builds? Which other unwanted side effects could this cause?
推荐答案
您绝对应该不编译-Ounchecked
以便发布,以便仅在测试时使用precondition
.编译-Ounchecked
还会禁用对数组越界和展开nil
之类的检查,这可能会导致涉及内存损坏的一些非常讨厌的生产错误.
You should definitely not compile -Ounchecked
for release in order to use precondition
only while testing. Compiling -Ounchecked
also disables checks for things like array out of bounds and unwrapping nil
, that could lead to some pretty nasty production bugs involving memory corruption.
您可以通过swiftc
的-assert-config
参数独立于编译器优化设置来控制断言行为:
You can control assertion behaviour independently of compiler optimization settings via the -assert-config
argument to swiftc
:
$ cat assert.swift
assert(false, "assertion asserted")
println("made it here...")
$ swiftc -Onone assert.swift; ./assert
assertion failed: assertion asserted: file assert.swift, line 1
Illegal instruction: 4
$ swiftc -O assert.swift; ./assert
made it here...
$ swiftc -O -assert-config Debug assert.swift; ./assert
assertion failed: assertion asserted: file assert.swift, line 1
Illegal instruction: 4
$
看起来没有Xcode Build Settings开关,但是您可以使用"Other Swift Flags"设置添加.
It doesn’t look like there’s an Xcode Build Settings toggle for this, but you can add using the "Other Swift Flags" setting.
这篇关于Swift -Ounchecked和断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!