当前位置 : 主页 > 手机开发 > 其它 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-11
源代码如下 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:\(userIma
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)
}
网友评论