If you’re new to Swift then you’ve likely noticed the three different types of Try statements – try, try! And try?
In order to understand the different try statements we first need to know how to declare errors, Swift provides a nice way for doing this using enums like in this example:
enum CorrectError: Error {
// specific case for error, nice way to create many different errors easily
case Wrong
}
Functions throw errors in Swift by using the throws keyword which is placed before the return arrow (the ->) like the throwing function in this example:
func isRight() throws -> Bool {
throw CorrectError.Wrong
// return statement never executes
return true
}
In order to utilize a throwing function one of the 3 different try statements.
The try keywords is used within the do -> catch statement like below, typically you’ll use this when you want to catch different types of errors:
// try isRight function
let answer = try isRight()
// never printed because of thrown error
print("it is right")
} catch CorrectError.Wrong{
// this gets printed because of error
print("Wrong")
}
The try! keyword expects a normal type so function being executed must not throw any error at all or the program will crash with a fatal error as nil is returned.
let answer = try! isRight()
// never executed because of error
print ("is right")
The try? keyword returns an optional type so if the function throws an error this value is nil.
let answer = try? isRight()
if answer != nil {
// won’t print because of thrown error
print("is right")
} else {
// prints because of thrown error
print ("Wrong")
}
As you can see Swift provides a nice syntax for handling errors. This is a vast improvement over error handling in the original release of Swift, and in Objective-C.
Original article: Try Catch in Swift – A Quick Guide To Basic Error Handling With Try, Try? & Try!
©2019 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.