当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - know the highest digit of a number

问题描述:

I'm doing an app in Xcode 8 with swift 3 that is a base converter, the input value is set with buttons:

@IBAction func inputButton(_ sender: UIButton)

{

currentNumber = currentNumber * 10 + (the number I want to add)

labelText.text = "\(currentNumber)"

}

It works perfectly, but when I input about 10 numbers the app crashes. After the line where I set the new value for "currentnumber" Xcode shows me this:

Thread1: EXC_BAD_INSTRUCTION (code=EXC_INPOV, subcode=0x0)

网友答案:

Overflow is (thankfully) an error in Swift.

You can prevent this in your code by checking if values would exceed Int.max, before actually performing the calculation.

Here's some code to get you started:

guard let inputNumber = Int(inputString) else {
    labelText.text = "input not a number or out of range"
    return
}

guard currentNumber < (Int.max - inputNumber) / 10 else {
    labelText.text = "overflow"
    return
}

currentNumber = currentNumber * 10 + inputNumber
labelText.text = "\(currentNumber)"
分享给朋友:
您可能感兴趣的文章:
随机阅读: