Curious about try?NSData(contentsOFURL)

Hi fellows,

I’m curious about what
try?NSData(contentsOFURL)

would return if the file doesn’t exist. I didn’t see the tutorial checks if the file exists, however, my app gets crushed without checking the existence of the file. I could not find details of this problem, I hope anyone knows and explains a bit to me.

Thanks!

That should return nil. Normally Data throws an error if the file cannot be found, but because you’re writing try? this gets turned into an optional.

Thanks, I thought there would be something like throw

There is, but you specified try? - the ? is important.

If you use try then you’ll need a do { try ... } catch { ... } statement to catch the error and respond accordingly.
If you use try? then the function’s return type will be treated as an optional and will return nil if there’s an error.
It’s a bit more complicated than that - if the function normally returns an optional (e.g an Int?), that optional will be wrapped in a second optional by the try? (e.g. it’ll now return an Int??). If the function returns nil legitimately, without throwing an error, you’ll still need to unwrap the value to find out if it was nil.

For the sake of completeness, there’s also try!, which if you use it and an error occurs, you’ll have a runtime error and your code will crash.

This topic was automatically closed after 166 days. New replies are no longer allowed.