iOS Swift - EXC_BAD_INSTRUCTION on certain devices

蓝咒 提交于 2019-12-23 02:32:12

问题


I'm very new to Swift and iOS development but I've come across a bug that is causing my app to crash when running on the following devices:

iPhone 4S iPhone 5 iPad 2 iPad Retina

Here is the code that is being flagged up:

// bin2dec - converts binary string into decimal string
func bin2dec(input: String) -> String {
    var counter = countElements(input)
    var digit: Character
    var power = 1
    var result = 0

    while counter > 0 {
        digit = input[advance(input.startIndex, counter-1)]

        switch digit {
        case "0":
            result += 0
        case "1":
            result += 1 * power
        default:
            power = power / 2
            break
        }
        counter--
        power *= 2
    }
    return "\(result)"
}

and the error is:

Thread 1: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)

Any help would be appreciated, thanks!


回答1:


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?.



来源:https://stackoverflow.com/questions/28344663/ios-swift-exc-bad-instruction-on-certain-devices

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