-3

I'm trying to unwrap these Int values that I receive from the server, but everything I've tried it just doesn't work. It keeps printing:

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

    })
}

enter image description here

Sorin
  • 43
  • 1
  • 5
  • if let variable = ... – El Tomato Mar 11 '17 at 01:49
  • it doesn't work, it still prints Optional(1) – Sorin Mar 11 '17 at 01:50
  • You need to go back to books. – El Tomato Mar 11 '17 at 01:52
  • 2
    All of those `!` - my eyes! Make it stop. Seriously, you do know that your code is going to crash due to the misuse of the `!` operator, right? Please spend some quality time reading up on optionals and safe unwrapping in the Swift book. – rmaddy Mar 11 '17 at 01:52
  • Nothing else worked, I just copy paste this last try and yes I know it isn't good at all. if let a = jsonData.value(forKey: "roomId") as! Int this was the previous try – Sorin Mar 11 '17 at 01:56
  • What do you mean by 'nothing else worked'? When? You did it yesterday? Or two days ago? You have no single if-statement to unwrap a mysterious variable which might or might not have a value. – El Tomato Mar 11 '17 at 02:11
  • if let id = jsonData.object(forKey: "playerId") as? Int{ self.playerId = id }. This doesn't work for example, neither with as! or jsonData.value(..) – Sorin Mar 11 '17 at 02:14
  • If you option-click on jsonData, what does Xcode say? If you option-click on data, what does Xcode say? – El Tomato Mar 11 '17 at 02:20
  • it says jsonData: NSDictionary – Sorin Mar 11 '17 at 02:23
  • Thanks - I just found my answer from Your question... – Ripa Saha Mar 17 '19 at 17:26

2 Answers2

1

Avoid using ! directly because if the value is nil and you try to access it will crash the application. So the best way to do it is either use if let or guard let statements. For example check below:

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

Using guard let:

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

print("\(safePlayerID)   \(saferoomID)")
Parth Adroja
  • 13,198
  • 5
  • 37
  • 71
0

That's how optionals print. If you don't want that, then you have to unwrap them before printing them. Keep in mind that the comments on your question are valid, and the "!" will almost certainly crash you at some point. But just for brevity, you can do this:

print("\(self.roomId!)   \(self.playerId!)")
ghostatron
  • 2,620
  • 23
  • 27
  • Thanks a lot! This was the fix I needed, now I can use those values :) – Sorin Mar 11 '17 at 02:30
  • 2
    This is a bad idea. This will crash if those values aren't set. The answer by Party is much, much better than slapping on `!`. – rmaddy Mar 11 '17 at 03:17
  • So you downvote me because you disagree with what is still a correct solution. And you also basically repeated exactly what I stated in my answer. Gee, thanks. And at least I explain WHY he's seeing what he's seeing. – ghostatron Mar 12 '17 at 05:56