0
guard let json = try? NSJSONSerialization.JSONObjectWithData(data!,
      options: []) as? [String: AnyObject] else {
        print("Nil data received from fetchAllRooms service")
        return
    }

In the above code I am unable to understand what is the significance of

  1. "try?": Is the "try?" here means the whole code after try will be under try block (same as try catch as in other language?)

  2. "as?" : It is for typecasting I guess. but why this "?", after as?

How can I replace the above code with if-let?

user804417
  • 155
  • 2
  • 13
  • 5
    http://stackoverflow.com/questions/32256834/swift-2-0-guard-vs-if-let – Jitendra Modi Dec 26 '16 at 05:21
  • read this out first https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html – Bhavin Bhadani Dec 26 '16 at 05:24
  • 2
    The `try?` returns optional value, which is `nil` if there was any error, but doesn't identify what the error was. So, if you don't care why it failed, the `if let foo = try? ... { .... }` (or the `guard` version) is concise alternative to the more cumbersome `do`-`catch` pattern. With the `as?` syntax, you're also safely checking that not only was there no error, but that the result was of the expected type, too. Clearly, if you need to know _why_ it failed, though, the `do`-`try`-`catch` pattern is essential. In terms of `if let` vs `guard let`, see the answers under the duplicate question. – Rob Dec 26 '16 at 06:13

0 Answers0