Nathan McKaskle
Nathan McKaskle

Reputation: 3063

Why does localizedDescription of NSError say Optional("description")?

Whenever I do println(error.localizedDescription) I get something that says :

Optional("description of the error here")

Rather than just:

"description of the error here"

How do I get rid of the Optional() part of the description?

I tried the below method which results in a compiler error saying that it's not an 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"])
                }
            }

        }
    }

Upvotes: 0

Views: 1552

Answers (2)

Dave Roberts
Dave Roberts

Reputation: 672

The compiler is correct - error is an optional but error.localizedDescription is not. You either need to unwrap the error first, safely by

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

or: Use optional chaining - https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

let description = error?.localizedDescription

which will either cause 'description' to be the string of localizedDescription, if the error optional can be unwrapped successfully, or possibly 'nil' if not.

Code taken from example added to question. Seems to work as ok, below code can be copied into playground to show error and data string printout - just add valid http:// address into see valid return or try with just 'http:' to get an error.

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()

Upvotes: 1

Aaron Brager
Aaron Brager

Reputation: 66242

You have to unwrap error using ?:

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

If you already know from an earlier check that error isn't nil, you can force unwrap:

println(error!.localizedDescription) 

This will crash if error is nil, so use the ! syntax with caution.

Upvotes: 0

Related Questions