简体   繁体   中英

Unwrapping error with optional in Swift

I'm trying to make some connections with an API and I need to return an error message if the username is unknown. Though, while I try to print my variable in my post request, I see the message but if I print my variable after my request but in my function, I have an error: fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) .

Here is a sample of my code. I use SwiftHTTP for my requests:

var errSign: String?
func signUp(email:String, pwd:String) {
    let params: Dictionary<String,AnyObject> = ["password": pwd, "email": email]

    task.POST(signUpUrl, parameters: params, completionHandler: {(response: HTTPResponse) -> Void in
        if let err = response.error {
            println("error: \(err.localizedDescription)")
        }
        if let json = response.responseObject as? Dictionary<String, AnyObject> {
            var data = JSON(json)
            if data["error"] != false {
                self.errSign = String(stringInterpolationSegment: data["error"])
                println(self.errSign!)
            }
        }
    })
    // ERROR println(self.errSign!)
}

You've declared errSign as optional, so you should probably check to see that there's something in there before attempting to print anything out:

self.errSign = String(stringInterpolationSegment: data["error"])
if let actualErrSign = self.errSign
{
    println(\(actualErrSign))
} else {
    println("no (obvious) error was returned")
}

the ! keyword is to unwrap an optional variable to access to its value. This is only possible when your optional variable contains a value. In case you try to unwrap an optional variable that does not hold actually a value, your application will crash and it receive that fatal error.

The solution is in the answer of @Michael Dautermann

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM