fatal error: unexpectedly found nil while unwrapping an Optional value in Swift

我的梦境 提交于 2020-01-05 02:32:43

问题


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)

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


回答1:


Try this way I think this will work :

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

    }



回答2:


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!




回答3:


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.



来源:https://stackoverflow.com/questions/26701993/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-value-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!