问题
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 data parameter returns nil, and error returns something. In iOS 8 this was expected functionality and we simply used if statements to find out whether or not Data was nil
However with do
catch
, there is the new try
keyword which I thought was meant to see if something works, if it doesn't then default to whatever code is written in catch
However, because data is nil I am getting an unexpected crash. Is this expected functionality, why isn't catch
being called when my try
method fails?
I'm using NSURLSession to pull data from an API.
I create a dataTaskWith request like this:
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
print(request)
print(response)
print(error)
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
Crashes right here because data! is nil.. because there was an NSURLSession error
print(jsonResult)
} catch {
print(error)
}
})
task.resume()
回答1:
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)
}
来源:https://stackoverflow.com/questions/32187683/swift-2-ios-9-do-catch-try-crashing-with-unexpected-nil-found