Ferrakkem Bhuiyan Ferrakkem Bhuiyan - 7 months ago 151
Swift Question

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

Answer

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