Value of optional type 'String?' not unwra

2019-06-13 16:40发布

Sorry new to all this, but could do with a hand. Realise its probably a very simple solution, but here is my troublesome code:

@IBAction func loginAction(sender: AnyObject) {

    var username = self.usernameField.text
    var password = self.passwordField.text

    if (count(username.utf16) < 4 || count(password.utf16) < 5) {

        var alert = UIAlertView(title: "Invalid", message: "Username must be greater then 4 and Password must be greater then 5", delegate: self, cancelButtonTitle: "OK")
        alert.show()

    }else {

        self.actInd.startAnimating()

        PFUser.logInWithUsernameInBackground(username, password: password, block: { (user, error) -> Void in

            self.actInd.stopAnimating()

            if ((user) != nil) {

                var alert = UIAlertView(title: "Success", message: "Logged In", delegate: self, cancelButtonTitle: "OK")
                //alert.show()

                self.navigationController!.popToRootViewControllerAnimated(false)

            }else {

                var alert = UIAlertView(title: "Error", message: "\(error)", delegate: self, cancelButtonTitle: "OK")
                alert.show()

Photo of Errors: Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'

2条回答
Explosion°爆炸
2楼-- · 2019-06-13 17:07

The error message is pretty much self-explanatory, you need to unwrap the optionals. outlets are optionals so both usernameField.text and passwordField.text return a type String? (The type is optional string, not string) so you can't do any string related unless you unwrap it to be String. here is how you can do that

if  let username = self.usernameField.text, password = self.passwordField.text {
    //your code
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-13 17:26

The purpose of optionals in Swift is to reduce the number of runtime errors. It allows the code to recognize when a variable has no value. 'no value' is different from nil and all other values.

When you reference an optional type you can force the compiler to get the value from the variable by adding an ! to the name. This should only be done when you are absolutely certain that there is a value to access. If you do this and no value is defined, your app will have a runtime error (crash). The optional can also be tested with an if to see if it has a value.

Think of this error message as a warning to you to check for a possible failure point.

查看更多
登录 后发表回答