1

I am trying to create a course avg calculator with textfields. However if I only want to enter in a few marks (i.e. not filling out all the textfields) I get a crash.

I get this error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

In my code, I tried to avoid this nil value, but I get the error on that first line if I leave the first textfield blank. I do further calculations with these textfields, so I'm not sure if I will get similar errors once I fix these lines.

    if b?.text != nil {
        b?.text = String(Double(b!.text!)!/100)
    }
    if d?.text != nil {
        d?.text = String(Double(d!.text!)!/100)

    }
    if f?.text != nil {
        f?.text = String(Double(f!.text!)!/100)
    }
    if h?.text != nil {
        h?.text = String(Double(h!.text!)!/100)
    }
MontgommeryJR
  • 255
  • 3
  • 18
  • 1
    From docs (about `text` property of `UITextField`): This string is @"" by default. So even if `text` property is of type `String?` in most cases it's not `nil`. Maybe better for you would be checking if `text` isn't empty: `if !textField.text.isEmpty` – Robert Dresler Dec 06 '18 at 20:53

2 Answers2

0

Force unwrap the double conversion

Double(b!.text!)!

is the reason as empty string can't be converted to double so it returns nil and as you use ! , hence the crash , you need

if let tex = b , content = tex.text ,  value = Double(content) {
   print(value)
}

Also don't make the b var an optional make it !

 var b:UITextField! // and make sure you init it 

Edit: Don't create other vars to hold instance ones use them directly

@IBOutlet weak var weight1: UITextField!

if let content = weight1.text ,  value = Double(content) {
   print(value)
   weight1.text = "\(value/100)"
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0
Double(b!.text!)! 

This is the reason, your input text (b!.text!) is not convertible to double hence ended up with nil.

for ex: you might be giving input "12Th45", this is not convertible to double.

Always use optional binding wherever you are not sure that value is there or not.

Thanks.

Neelam Verma
  • 3,232
  • 1
  • 22
  • 33