Kiyoung choi Kiyoung choi - 4 days ago 4
iOS Question

Swift, Thread 1: EXC_BAD_INSTRUCTION error

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var currencySegment: UISegmentedControl!

@IBOutlet weak var sourceMoneyField: UITextField!

@IBOutlet weak var targetMoneyLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func convertMoney(_ sender: Any) {
let ratio : Double
switch currencySegment.selectedSegmentIndex {
case 0:
ratio = 0.00085
case 1:
ratio = 1178.5
default :
ratio = 1.0
}
let targetMoneyString: String
if let sourceMoney = Double(sourceMoneyField.text!){
targetMoneyString = "\(sourceMoney * ratio)"
}else {
targetMoneyString = "Error"
}

targetMoneyLabel.text = targetMoneyString
}
}


In the last part, I get error which is:


thread 1: exc_bad_instruction(code=exc_i386_invop,subcode=0x0) error


To the
targetMoneyLabel.text = targetMoneyString
part.

I think I have to change last sentence, I try to read and watch many videos to fix it, but I can't.

Is the problem related to
nil
? I am new to Swift.

Answer

The problem must be about unwrapping the variable.

You can try this:

guard let targetMoneyString.characters.count > 0 else  {
    return
}
targetMoneyLabel.text = targetMoneyString
Comments