Kiyoung choi Kiyoung choi - 1 year ago 68
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() {
// Do any additional setup after loading the view, typically from a nib.
override func 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

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
? I am new to Swift.

Answer Source

The problem must be about unwrapping the variable.

You can try this:

guard let targetMoneyString.characters.count > 0 else  {
targetMoneyLabel.text = targetMoneyString
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download