Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

Downcast from 'String?!' to 'String' only unwraps optionals; did you mean to use '!!'? in swift

enter image description here

source-code are bellow

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                        if let blogs = json["profile_image_url"] as? String {

                            userImage = blogs//json["profile_image_url"] as! String
                            print("USER IMAGE:\(userImage)")

how i solve this issue

Upvotes: 3

Views: 6866

Answers (1)

user887210
user887210

Reputation:

You want to test and unwrap any Optional before you use them. This includes casts like as?. If you can avoid it you should not use forced-unwrapping or explicitly-unwrapped Optional (marked with a !) because they lead to unexpected runtime crashes.

import Foundation

// create test data
let testJson = ["profile_image_url": "http://some.site.com/"]
var data: NSData?

// convert to NSData as JSON
do {
  data = try NSJSONSerialization.dataWithJSONObject(testJson, options: [])
} catch let error as NSError {
  print(error)
}

// decode NSData
do {
  // test and unwrap data
  if let data = data {
    let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
    // test and unwrap cast to String
    if let userImage = json["profile_image_url"] as? String {
      print("USER IMAGE:\(userImage)")
    }
  }
} catch let error as NSError {
  print(error)
}

Upvotes: 7

Related Questions