【问题标题】:Why does localizedDescription of NSError say Optional("description")?为什么 NSError 的localizedDescription 说 Optional("description")?
【发布时间】:2015-07-11 17:04:16
【问题描述】:

每当我做println(error.localizedDescription) 时,我都会得到以下信息:

可选的(“这里的错误描述”)

而不仅仅是:

“这里的错误描述”

如何去掉描述中的Optional() 部分?

我尝试了以下方法,导致编译器错误说它不是可选的。

func performLoginRequestWithURL(url: NSURL, email: String, password: String) {
        let bodyData = "email=\(email)&password=\(password)"
        var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()){
            response, data, error in

            if let error = error {
               let errString = error.localizedDescription
               NSNotificationCenter.defaultCenter().postNotificationName(self.lh, object: nil, userInfo: ["Result": errString])

            } else if data != nil {
                let json = NSString(data: data, encoding: NSUTF8StringEncoding) as! String

                if let dictionary = JSON().parseJSON(json) as [String: AnyObject]? {
                    let accesstoken = dictionary["id"] as! String
                    let id = dictionary["userId"] as! Int
                    var results = [String: AnyObject]()
                    results = ["at": accesstoken, "id": id]

                    // MARK: - Store UID & AccessToken
                    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "userLoggedIn")
                    NSUserDefaults.standardUserDefaults().setInteger(id, forKey: "userId")
                    NSUserDefaults.standardUserDefaults().setObject(accesstoken, forKey: "accessToken")
                    NSUserDefaults.standardUserDefaults().synchronize()
                    NSNotificationCenter.defaultCenter().postNotificationName(self.lh, object: nil, userInfo: ["Result": "Success"])
                }
            }

        }
    }

【问题讨论】:

    标签: string swift optional nserror


    【解决方案1】:

    编译器是正确的 - error 是可选的,但 error.localizedDescription 不是。您需要先安全地解开错误

    if let unwrappedError = error {
         println(unwrappedError.localizedDescription)
    }
    

    或者:使用可选链接 - https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

    let description = error?.localizedDescription
    

    如果错误可选可以成功解包,这将导致'description'成为localizedDescription的字符串,否则可能是'nil'。

    取自示例的代码已添加到问题中。似乎工作正常,下面的代码可以复制到 Playground 以显示错误和数据字符串打印输出 - 只需将有效的 http:// 地址添加到查看有效返回或尝试仅使用 'http:' 来获取错误。

    import UIKit
    import XCPlayground
    
    func performLoginRequestWithURL(url: NSURL) {
        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()){
            response, data, error in
    
            if let error = error {
    
                let errString = error.localizedDescription
    
                print(errString)
    
            } else if data != nil {
    
                let json = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
    
                print(json)
            }
        }
    }
    
    performLoginRequestWithURL(NSURL(string:"http:")!)
    
    XCPSetExecutionShouldContinueIndefinitely()
    

    【讨论】:

    • 我已经尝试过使用 if let error = error { ... } 的那部分(见上文)。现在就是这样,error.localizedDescription中的错误就是从这里来的。
    • 这个 NSError 是从哪个类生成的?
    • 来自 NSURLConnection,它是一个对远程服务器的 POST 请求。
    • 您能否为您的问题添加尽可能多的完整代码块 - 如有必要,将 http 地址、发送的确切信息等空白,以便对具体问题进行调查?
    • 抱歉,这里似乎一切正常,我添加了代码来回答复制并粘贴到游乐场以显示非可选的 error.localizedDescription
    【解决方案2】:

    您必须使用? 解开error

    if let errString = error?.localizedDescription { 
      println(errString) 
    }
    

    如果您从之前的检查中已经知道 error 不是 nil,则可以强制解包:

    println(error!.localizedDescription) 
    

    如果errornil,这将崩溃,因此请谨慎使用! 语法。

    【讨论】:

    • 我已经把它放在一个检查中,看看错误是否不为零,但它仍然坚持它不是可选的。所以这两个选项都行不通。错误说操作数应该是可选类型。
    • 我用的是最新的,6.4
    猜你喜欢
    • 2017-04-15
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多