看了一下这些文档后(如果有答案,我很抱歉,我还不能理解那里写的所有内容......还在学习)并在google上搜索答案,我遇到了这个解决方案:
(其中Peso,Meta和Coef是浮点数,pesoInput和metaLabel是字符串)
peso = (pesoInput.text as NSString).floatValue
meta = peso * coef
metaLabel.text = NSString(format: "%.2f", meta)
如您所见,我需要执行定义" meta"的操作。然后在UILabel metaLabel中显示它。
我设置println命令打印三个浮点数,所有这些都是正确的,包括操作结果。
但是,它在控制台中给出了这个错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
编辑器上的此错误:
Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOC, subcode=0x0)
您知道,在Debug区域中,唯一存在的nil值是:
metaLabel = (UILabel!) = nil
故事板中的metaLabel不是空的,它被设置为0.01,因为我测试的是看是否为0.00的事实是否来自nil ...
需要帮助,伙计们!谢谢!
编辑:
这里是整个代码,伙计们:
import UIKit
import Foundation
class ViewController: UIViewController{
//Vars Sexo, Peso e Coef
var sexo = ""
var peso : Float = 0.0
var coef : Float = 0.039
var meta : Float = 0.0
//Alerta
var tituloalertaPeso = "Peso Inválido"
var mensagemalertaPeso = "Por favor, cheque o peso!"
@IBAction func botaoMasc(sender: AnyObject) {
var sexo = "masculino"
}
@IBAction func botaoFem(sender: AnyObject) {
var sexo = "feminino"
}
@IBOutlet weak var pesoInput: UITextField!
@IBOutlet weak var metaLabel: UILabel!
@IBAction func okConfig(sender: AnyObject) {
metaLabel.text = "0.01"
//CONVERSAO STRING -> FLOAT
if (pesoInput.text as NSString).floatValue < 10 || (pesoInput.text as NSString).floatValue > 160 {
let alertaPeso = UIAlertController(title: "Peso Inválido", message:
"Por favor, precisamos do seu peso para fazer os cálculos!", preferredStyle: UIAlertControllerStyle.Alert)
alertaPeso.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertaPeso, animated: true, completion: nil)
}
else {
peso = (pesoInput.text as NSString).floatValue
meta = peso * coef
// THE FOLLOWING LINE IS THROWING THE EXC:
metaLabel.text = NSString(format: "%.2f", meta)
}
}
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.
}
}
答案 0 :(得分:0)
我认为这与行peso = (pesoInput.text as NSString).floatValue
有关。如果您的文字为空,我相信它会从该演员表中返回nil
。此时,您尝试从floatValue
值获得nil
。
答案 1 :(得分:0)
如果metalabel
为nil
,则当您访问其fatal error: unexpectedly found nil while unwrapping an Optional value
属性(text
)时,您将获得metalabel.text = "something"
。
您应该检查xib的metalabel
插座连接。
也许您没有将xib连接到视图控制器:https://stackoverflow.com/a/6395750/3438932
或者连接断开:尝试断开连接并重新连接插座。