iOS Swift - EXC_BAD_INSTRUCTION on certain devices

2019-06-06 12:36发布

问题:

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