0

I am writing an app for a fencing company where the user can specify how many meters of fence they require and it will calculate the number of panels, feet and clamps needed for that meterage, I also have 2 fields where they can add additional clamps and additional feet to their order when they do this it automatically updates the values it calculated before to include the extras.

This works fine so long as the text field always has a number in it, for example, if you enter 30m into the first box the app would work out that you need 31 feet, if I put 3 additional feet on the order it says 34 feet, if I then change my mind and delete the contents of the extra feet field the app crashes due to finding nil while unwrapping an optional value, is there a way I can get around this?

I have the following code:

@IBAction func AdditionalFeetField(sender: AnyObject) {
    if AdditionalFeetField.text != nil {
        let AdditionalFeetValue1 = Double(PanelQtyField.text!);
        let AdditionsFeetValue2 = Double(AdditionalFeetField.text!);
        let AdditionalFeetResult = (AdditionalFeetValue1! + AdditionsFeetValue2!) + 1
        self.FeetQtyLabel.text = "\(AdditionalFeetResult)"
    }
 }

`

Hamish
  • 78,605
  • 19
  • 187
  • 280
DanielPetters386
  • 133
  • 1
  • 1
  • 6
  • http://stackoverflow.com/questions/30315723/check-if-string-is-a-valid-double-value-in-swift - the top answer is a great way of checking that a string is numeric and castable to a double. Be sure to check that your `textfield.text` is not nil. – Mattias Apr 06 '16 at 09:35
  • 2
    Never force unwrap an optional. You're just asking for a crash. Please learn how to [properly deal with them.](http://stackoverflow.com/a/36360605/2976878) – Hamish Apr 06 '16 at 09:56

1 Answers1

1

When you're using ! you are force unwrapping the values of the text fields in this case, meaning that you say to the compiler "Just give me the value of the text field, I don't care if it is nil or not". This is almost always a bad idea...as you've found out :-)

A better way is to use if let or guard to unwrap the values.

I've tried to update your function to use if let

@IBAction func AdditionalFeetField(sender: AnyObject) {
    if let additionalFeetStringValue = AdditionalFeetField.text,
       let panelQtyFieldStringValue = PanelQtyField.text {
        let additionalFeetValue1 = Double(panelQtyFieldStringValue) ?? 0
        let additionsFeetValue2 = Double(additionalFeetStringValue) ?? 0
        let additionalFeetResult = (additionalFeetValue1 + additionsFeetValue2) + 1
        FeetQtyLabel.text = "\(AdditionalFeetResult)"
     }
}

(I took the liberty of deleting your semicolons and self references too :-))

Hope that helps you. Maybe you can combine it with @mattias suggestion about checking if the value can be cast to a double.

pbodsk
  • 6,787
  • 3
  • 21
  • 51