0

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.
}


}
  • From which function (e.g. viewDidLoad() ...) is called your piece of code? – Jérôme Feb 18 '15 at 22:30
  • It is in an IBAction, I'll post the whole code! – Caio Frison Feb 18 '15 at 22:33
  • 1
    Please indicate the line throwing the exception – qwerty_so Feb 18 '15 at 23:02
  • Hi @ThomasKilian, the line is metaLabel.text = NSString(format: "%.2f", meta). I'll indicate it in the post aswell. Thanks – Caio Frison Feb 19 '15 at 00:09
  • Hey guys, found the problem. It's embarrassing haha. For those out there with the same problem: The problem was that my okConfig button called a new modal view controller, and the label I was trying to set the value on was on this new viewcontroller. I put a label just for testing in the same view controller of the button and it worked. Thank you all!! Learned a lot from all the help, too. – Caio Frison Feb 19 '15 at 00:34

2 Answers2

0

I believe it has something to do with the line peso = (pesoInput.text as NSString).floatValue. If your text is empty, I believe it returns nil from that cast. At that point, you're trying to get a floatValue from a nil value.

AdamPro13
  • 7,232
  • 2
  • 30
  • 28
  • I'm sorry, I didn't post the whole code. Looking at that piece of code, it does make sense! However, peso value comes from a textfield input (pesoInput) that is filled before the whole operation starts, so I don't think that is the issue. – Caio Frison Feb 18 '15 at 22:38
0

If metalabel is nil you will get fatal error: unexpectedly found nil while unwrapping an Optional value when you access its text property (metalabel.text = "something").

You should check metalabel outlet connection to the xib.

Maybe you did not connect the xib to your view controller: https://stackoverflow.com/a/6395750/3438932

Or maybe the connections are broken: try disconnect and reconnect the outlet.

Community
  • 1
  • 1
kanobius
  • 756
  • 9
  • 12