2
votes

So I'm trying to get the text of an input field in Swift. So here's what I got

class ViewController: UIViewController {

    @IBOutlet var passwordField: UITextField!
    @IBOutlet var usernameField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()            
        //Try to log user in by default
        let user = usernameField.text
        let password = passwordField.text

It all looks good (I know I didn't close the class, I just pulled it directly out) and when I go to run it, I get

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

and

You'll have to open the image in a new tab to see it

(You'll have to open the image in a new tab to see it)

I binded the input fields with the IBOutlet successful, I know that. Any ideas?

3
The problem appears to be that usernameField is nil at the point you are trying to access it, and so trying to access .text fails. I personally find that surprising, since it seems that it should be assigned by the time viewDidLoad is called. (Unless the fields are not actually in the view). In any case, use conditional unwrapping to avoid the error. As a side note, why are you checking the values at the beginning of viewDidLoad? It seems unlikely that there would be any text in them at that point.dustincarr

3 Answers

2
votes

Try this way I think this will work :

if let abc = usernameField.text{
        let user = abc

    }
0
votes

i think You Have to Check This in TextField's Delegate Method

func textFieldDidEndEditing(textField: UITextField) {

}

instead ViewDidLoad Or On Action of ButtonClick

Cause TextField Are Empty On ViewDidLoad!

0
votes

I had this problem while setting the delegate to a text field. Couldn't figure out was wrong then realized that I had declared the class for a second view controller as a view controller not a UIViewController. I'm new at this.