Diego Esc Diego Esc - 1 year ago 72
iOS Question

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)

Answer Source

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"

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

currentNumber = currentNumber * 10 + inputNumber
labelText.text = "\(currentNumber)"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download