iOS Swift-某些设备上的EXC_BAD_INSTRUCTION [英] iOS Swift - EXC_BAD_INSTRUCTION on certain devices

查看:191
本文介绍了iOS Swift-某些设备上的EXC_BAD_INSTRUCTION的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Swift和iOS开发非常陌生,但是遇到了一个错误,该错误导致在以下设备上运行时我的应用崩溃:

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

iPhone 4S iPhone 5 iPad 2 iPad Retina

这里是被标记的代码:

// 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)"
}

,错误是:

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

任何帮助将不胜感激!

推荐答案

iPhone 4S,iPhone 5,iPad 2,iPad Retina是32位设备,其中 Int
是一个32位整数。因此,以

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

然后调用

power *= 2

32次将溢出并导致异常。在Swift中,除非您明确使用溢出运算符 & * ,否则整数算法不会像(Objective-)C,
中那样默默地环绕, & + 等。

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.

可能的解决方案:


  • 使用 Int64 代替 Int

  • 避免最后乘以次幂(其结果不需要
    )。

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

这篇关于iOS Swift-某些设备上的EXC_BAD_INSTRUCTION的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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