从’String ?!’垮掉’String’只展开选项;你的意思是用’!!’吗?在迅速

前端之家收集整理的这篇文章主要介绍了从’String ?!’垮掉’String’只展开选项;你的意思是用’!!’吗?在迅速前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

enter image description here

代码如下

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

我是如何解决这个问题的

解决方法

您希望在使用之前测试和解包任何Optional.这包括像?的演员表.如果你可以避免它,你不应该使用强制解包或显式解包的Optional(用!标记),因为它们会导致意外的运行时崩溃.

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

猜你在找的Swift相关文章