Swift -Ounchecked和断言 [英] Swift -Ounchecked and Assertions

查看:176
本文介绍了Swift -Ounchecked和断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆