iOS Swift - EXC_BAD_INSTRUCTION on certain devices

只愿长相守 提交于 2019-12-06 15:29:54
Martin R

iPhone 4S, iPhone 5, iPad 2, iPad Retina are 32-bit devices, where Int is a 32-bit integer. Therefore starting with

var power = 1

and then calling

power *= 2

32 times will overflow and cause an exception. In Swift, integer arithmetic does not silently "wrap around" as in (Objective-)C, unless you explicitly use the "overflow operators" &*, &+ etc.

Possible solutions:

  • Use Int64 instead of Int.
  • Avoid the final multiplication of power (whose result is not needed).

Note that there are simpler methods to convert a string of binary digits to a number, see for example How to convert a binary to decimal in Swift?.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!