-2

I have a textfield and I want it to hide and show when a button is pressed, and I also want the text in the textfield to be passed to a label just underneath the textfield. I tried this :

 @IBAction func myfunction(_ sender: UIButton) {
    if textfield.isHidden == true{
        textfield.isHidden = false
        }else{
            label.text = textfield.text
            textfield.isHidden = true
     }
 }

Apparently the hidding and showing part is working but the line

label.text = textfield.text

is not. I get an error like this "Thread 1: EXC_BREAKPOINT (code=1, subcode=0x10143fb50" and in the console I have "fatal error: unexpectedly found nil while unwrapping an Optional value"

Can someone help me please.

  • 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) – Shades Sep 23 '17 at 12:33

2 Answers2

1

Based on your error, it seems that you try to affect with this line label.text = textfield.text the text from your textfield into label but the problem is that your textfield.text is nil.

That's why you have the error unexpectedly found nil while unwrapping an Optional value

Your textfield is an Optional. It can have a value or nil. If you try to unwrap an optional value having nil you have this kind of error. The solution here is to unwrap safely the optional value with Optional Binding like this :

if let textInput = textfield.text {
  //There is a text in your textfield so we get it and put it on the label
  label.text = textInput 
} else {
  //textfield is nil so we can't put it on the label
  print("textfield is nil")
}
Arrabidas92
  • 1,113
  • 1
  • 9
  • 20
0

Here is a simpler code you may try. The nil-coalescing operator (a ?? b) unwraps an optional a. if it contains a value, or returns a default value b if a is nil.

@IBAction func myfunction(_ sender: UIButton) {
    label.text = textfield.text ?? "" 
}
Alf Bae
  • 546
  • 6
  • 10