如何从 NSDictionary 中解包可选值? - Swift

How to unwrap optional value from NSDictionary? - Swift

我正在尝试解包从服务器接收到的这些 Int 值,但我尝试过的所有方法都不起作用。它一直在打印:

"Optional(int value)".

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

    })
}

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

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

避免直接使用 !,因为如果值为 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 safePlayerID = self.playerId, let saferoomID = self.roomId else {
      return nil
}

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