【发布时间】: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