Home Ask Login Register

Developers Planet

Your answer is one click away!

SwiftDeveloper February 2016

Swift 2 Json NSDictionary to String gives Optional("String") Error

I have working json parsing codes and when i take example , post["name"] as? String gives output Optional("John")

I want only output = John

My codes here

func post(url : String, completionHandler : ((success : Int, message : String) -> Void)) {

        guard let url = NSURL(string: url as String) else {


        let urlRequest = NSURLRequest(URL: url)

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)

        let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
            guard let responseData = data else {

            guard error == nil else {


            let post: NSDictionary
            do {
                post = try NSJSONSerialization.JSONObjectWithData(responseData,
                    options: []) as! NSDictionary
            } catch  {


            // Add user limits to Session

            let name = post["name"] as? String

            print(name) // Here gives output Optional("John")

            let numberFromString = Int((post["success"] as? String)!)

            completionHandler(success: (numberFromString)!, message: (post["message"] as? String)!)



You can see my all working codes here. I want only output = John ,

Thank you.


dzk February 2016

You're printing an optional value, which means that you need to unwrap it. E.g.


But this will crash if name is nil.

Post Status

Asked in February 2016
Viewed 3,144 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life