Dmitry Memeboy Dmitry Memeboy - 5 months ago 17
Swift Question

Thread 1: EXC_BAD_INSTRUCTIONS | SWIFT

When i am starting the app, it runs normal. When i click randomize button, Thread 1: EXC_BAD_INSTRUCTIONS comes at

finalLABEL.text = str
point.
fatal error: unexpectedly found nil while unwrapping an Optional value

@IBOutlet var fromACT: UITextField!
@IBOutlet var toEXT: UITextField!
@IBOutlet var finalLABEL: UILabel!
func unsafeRandomIntFrom(start: Int32, to end: Int32) -> Int32 {
let number = Int32(arc4random_uniform(UInt32(end - start + 1))) + start
return number
}

@IBAction func random(sender: AnyObject) {
let convertedNumber = NSString(string: fromACT.text!).intValue
let convertedNumber2 = NSString(string: toEXT.text!).intValue
let randomSV = unsafeRandomIntFrom(convertedNumber, to: convertedNumber2)
let str = String(randomSV)

finalLABEL.text? = str
}

Answer

Try to protect your code :

...
let convertedNumber = NSString(string: fromACT.text!).intValue
let convertedNumber2 = NSString(string: toEXT.text!).intValue
let randomSV = unsafeRandomIntFrom(convertedNumber, to: convertedNumber2)
if Int(randomSV) != nil {
    let str = String(randomSV)
    finalLABEL.text? = str
}

You could set also a default values to your function:

func unsafeRandomIntFrom(start: Int32 = 3, to end: Int32 = 6) -> Int32 {
    let number =  Int32(arc4random_uniform(UInt32(end - start + 1))) + start
    return number
}

to ensure whenever you want to call your function without values, to have a default values.