简体   繁体   English

在Swift中使用可选的展开错误

[英]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. 我正在尝试与API建立一些连接,如果用户名未知,我需要返回错误消息。 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) . 虽然,当我尝试在发布请求中打印变量时,我看到了消息,但是如果我在请求后但在函数中打印变量,则出现错误: fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

Here is a sample of my code. 这是我的代码示例。 I use SwiftHTTP for my requests: 我对请求使用SwiftHTTP:

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: 您已将errSign声明为可选,因此在尝试打印出任何内容之前,您应该检查一下是否有东西:

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 解决方案是@Michael Dautermann的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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