【问题标题】:Swift, Thread 1: EXC_BAD_INSTRUCTION errorSwift,线程 1:EXC_BAD_INSTRUCTION 错误
【发布时间】:2016-12-01 11:08:44
【问题描述】:
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
}
}

在最后一部分,我得到错误是:

线程 1:exc_bad_instruction(code=exc_i386_invop,subcode=0x0) 错误

targetMoneyLabel.text = targetMoneyString 部分。

我想我必须改变最后一句话,我尝试阅读和观看很多视频来修复它,但我不能。

问题与nil有关吗?我是 Swift 新手。

【问题讨论】:

  • 您是否重新检查过您的插座是否正确连接?
  • 在我的操场上你的代码工作正常,我没有收到错误
  • if targetMoneyLabel != nil { targetMoneyLabel.text = targetMoneyString } 使用此代码而不是最后一行,如果应用没有崩溃,则必须重新连接插座
  • 在您的错误中,您删除了所有有用的信息。
  • 非常感谢,我使用了“ if targetMoneyLabel != nil { targetMoneyLabel.text = targetMoneyString } ”,我终于消除了我的错误

标签: ios objective-c swift


【解决方案1】:

问题一定是关于解包变量。

你可以试试这个:

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

【讨论】:

  • 我做到了,但它带来了另一个问题,即“条件中的变量绑定需要初始化器”。
  • 好消息是无论如何我修复了过去的错误。谢谢!你的建议太好了^^,我会继续努力的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多