how are you? I am new to iOS dev using Swift and came across a problem. I need to get a float result from an equation and set it to my label.text.
After taking a look at the docs (if the answer is there, I'm sorry, I am not yet capable of understanding all that is written on there... still learning) and searching for answers on google, I came across this solution:
(where Peso, Meta and Coef are floats and pesoInput and metaLabel are Strings)
peso = (pesoInput.text as NSString).floatValue
meta = peso * coef
metaLabel.text = NSString(format: "%.2f", meta)
As you can see, I need to perform the operations that will define "meta" and then show it in the UILabel metaLabel.
I set println orders to print the three floats and all of them are correct, including the operation result.
However, it gives me this error in the console:
fatal error: unexpectedly found nil while unwrapping an Optional value
This error on the Editor:
Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOC, subcode=0x0)
And just so you know, in the Debug area, the only nil value that exists is:
metaLabel = (UILabel!) = nil
The metaLabel in the storyboard isnt empty, it is set to 0.01, as I tested to see if the fact that is was 0.00 was originating the nil...
Need help, guys! Thanks!
EDIT:
Here's the whole code, guys:
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.
}
}