【问题标题】:How to unwrap optional value from NSDictionary? - Swift [duplicate]如何从 NSDictionary 中解开可选值? - 斯威夫特 [重复]
【发布时间】:2017-03-11 01:43:37
【问题描述】:

我正在尝试解开从服务器接收到的这些 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)
        }

    })
}

【问题讨论】:

  • 如果让变量 = ...
  • 它不起作用,它仍然打印 Optional(1)
  • 你需要回去看书。
  • 所有这些! - 我的眼睛!让它停下来。说真的,你知道你的代码会因为滥用! 操作符而崩溃,对吧?请花一些时间阅读 Swift 书中的可选选项和安全展开。
  • 没有其他工作,我只是复制粘贴最后一次尝试,是的,我知道它一点都不好。 if let a = jsonData.value(forKey: "roomId") as! Int 这是之前的尝试

标签: swift httprequest nsdictionary unwrap


【解决方案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 safePlayerID = self.playerId, let saferoomID = self.roomId else {
      return nil
}

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 非常感谢!这是我需要的修复,现在我可以使用这些值了 :)
    • 这是个坏主意。如果未设置这些值,这将崩溃。党的回答比拍!好得多。
    • 所以你对我投了反对票,因为你不同意仍然是正确的解决方案。而且您基本上也完全重复了我在回答中所说的内容。哎,谢谢。至少我解释了为什么他会看到他所看到的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2017-07-22
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多