Swift Enumerations supports Associated Values. It's an excellent feature to simplify your error handling code without throwing exceptions.
Very often, your app needs to run an operation (doSomething()
) that will either return a result if it runs successfully, or an error if it doesn't. The error is often represented by an error message, an error code, or both. There are several ways to do this without using enums. One of them being throwing an exception upon an error or always returning a tuple with 2 elements, 1 representing the successful value, the other representing the error. But with enums, you can do this:
enum Result<T> {
case Success(T)
case Failure(String)
}
func doSomething() -> Result<Int> {
return Result.Success(123)
//return Result.Failure("error message") //Uncomment this line to simulate error
}
var result = doSomething()
switch result {
case let .Success(val):
print("Did something successfully, returning value: \(val)")
case let .Failure(err):
print("Failed to do something with reason: \(err)")
}
Because you are using a switch statement, it also makes it impossible for you to forget about handling an enum state.
This technique is sometimes referred to as Result Enums.
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.
.