2

I'm getting the following error on button click

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

following is the code

@IBOutlet weak var UserId: UITextField!{
    didSet{
        UserId.setBottomBorder()
        UserId.delegate = self
    }
}
@IBOutlet weak var Password: UITextField!{
    didSet{
        Password.setBottomBorder()
        Password.delegate = self
    }
}

@IBAction func logincta(_ sender: Any) {
           guard let _ = UserId.text, UserId.text?.characters.count != 0 else {
        print("test")
        return
    }

}

but works fine in the following onchange code

@IBAction func UserIdChanged(_ sender: Any) {
    if UserId.text == "" {
        UserId.setBottomBorder()
    }
    else{
    UserId.setPurpleBottomBorder()
    }
}

@IBAction func PasswordChanged(_ sender: Any) {
    if Password.text == "" {
        Password.setBottomBorder()
    }
    else{
        Password.setPurpleBottomBorder()
    }
}

i wonder how it worked in onchange event "if UserId.text == "" but not in button click

  • Can you please show your `setBottomBorder` function. – iPeter Nov 28 '18 at 06:28
  • 1
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Kamran Nov 28 '18 at 06:41
  • check your textfield outlet reference – Shezad Nov 28 '18 at 06:56
  • but if the textfield reference is wrong it shouldn't work on change event.... but it works fine on that.... only on button click i get the error –  Nov 28 '18 at 07:00
  • @iPeter following is the code func setBottomBorder(){ self.layer.shadowColor = UIColor(red:193/255 , green:193/255 , blue:193/255 , alpha:100 ).cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) self.layer.shadowOpacity = 1.0 self.layer.shadowRadius = 0.0 } –  Nov 28 '18 at 07:01
  • Don't do in didSet of UITextField, viewDidLoad is the right place to work with IBOutlets. – vivekDas Nov 28 '18 at 07:18
  • Please share your full code. I need to to have a look into that. – Naresh Nov 28 '18 at 09:09

1 Answers1

0

I've tried your code and it seems to work...

Anyway maybe try to use the guard in this way:

guard let numOfChars = UserId?.text?.count, numOfChars != 0 else {
        print("test")
        return
    }
DungeonDev
  • 1,176
  • 1
  • 12
  • 16