Swift 2 iOS 9 Do Catch Try crashing with unexpected nil found

前端 未结 1 2005
天涯浪人
天涯浪人 2020-12-03 16:20

I\'m trying to become familiar with the new do catch statements with swift 2 and iOS 9

My problem is that when an error occurs with NSURLSession, the da

相关标签:
1条回答
  • 2020-12-03 17:05

    This is because catch only catches what a functions "throws".

    NSJSONSerialization throws, but force unwrapping an empty Optional doesn't, it always crashes.

    Use if let or the new guard function to safely unwrap your values.

    do {
        if let myData = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(myData, options: []) as? NSDictionary {
            print(jsonResult)
        }
    } catch {
        print(error)
    }
    
    0 讨论(0)
提交回复
热议问题