Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling try and throws in Swift 3

Tags:

ios

swift

swift3

Before Swift 3 I was using:

guard let data = Data(contentsOf: url) else {                 print("There was an error!)                 return             } 

However I now have to use do, try and catch. I'm not familiar with this syntax. How would I replicate this behaviour?

like image 976
KexAri Avatar asked Sep 28 '16 15:09

KexAri


People also ask

What is the difference between try and try in Swift?

Swift is much stricter with respect to error handling and that is a good thing. The syntax, for example, is much more expressive. The try keyword is used to indicate that a method can throw an error. To catch and handle an error, the throwing method call needs to be wrapped in a do-catch statement.

How do you use try catch in Swift?

try – You must use this keyword in front of the method that throws. Think of it like this: “You're trying to execute the method. catch – If the throwing method fails and raises an error, the execution will fall into this catch block. This is where you'll write code display a graceful error message to the user.


1 Answers

The difference here is that Data(contentsOf: url) does not return an Optional anymore, it throws.

So you can use it in Do-Catch but without guard:

do {     let data = try Data(contentsOf: url)     // do something with data     // if the call fails, the catch block is executed } catch {     print(error.localizedDescription) } 

Note that you could still use guard with try? instead of try but then the possible error message is ignored. In this case, you don't need a Do-Catch block:

guard let data = try? Data(contentsOf: url) else {     print("There was an error!")     // return or break } // do something with data 
like image 166
Eric Aya Avatar answered Sep 23 '22 12:09

Eric Aya