如何从NSDictionary中解包可选值? - 斯威夫特

时间:2017-03-11 01:43:37

标签: swift httprequest nsdictionary unwrap

我试图解开我从服务器收到的这些Int值,但我尝试过的所有内容都无法正常工作。它不断印刷:

  

"可选(int值)"。

var playerId, roomId : Int!

func makeGetRequest(path: String){
    let urlPath: String = "http://myServer.ddns.net:7878/\(path)"
    let url: NSURL = NSURL(string: urlPath)!
    var request1: URLRequest = URLRequest(url: url as URL)

    request1.httpMethod = "GET"
    let queue:OperationQueue = OperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1 as URLRequest, queue: queue, completionHandler:{ (response: URLResponse?, data: Data?, error: Error?) -> Void in

        do {
            let jsonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
            print("ASynchronous\(jsonData)")

            self.playerId = jsonData.value(forKey: "playerId") as! Int
            self.roomId = jsonData.value(forKey: "roomId") as! Int

           print("\(self.roomId)   \(self.playerId)")

        } catch let error as NSError {
            print(error.localizedDescription)
        }

    })
}

enter image description here

2 个答案:

答案 0 :(得分:1)

避免直接使用!,因为如果值为nil并且您尝试访问它将导致应用程序崩溃。因此,最好的方法是使用if letguard let语句。例如,请查看以下内容:

self.playerId = jsonData.value(forKey: "playerId") as! Int
self.roomId = jsonData.value(forKey: "roomId") as! Int

if let safePlayerID = self.playerId, let saferoomID = self.roomId {
     print("\(safePlayerID)   \(saferoomID)")
}

使用guard let:

guard let safePlayerID = self.playerId, let saferoomID = self.roomId else {
      return nil
}

print("\(safePlayerID)   \(saferoomID)")

答案 1 :(得分:0)

那是选项打印的方式。如果您不想要它,那么您必须在打印它们之前打开它们。请记住,您对问题的评论是有效的,并且"!"几乎肯定会在某些时候让你崩溃。但为了简洁起见,您可以这样做:

print("\(self.roomId!)   \(self.playerId!)")