Why use throw in this scenario or others? | Swift

Viewed 45

Essentially while this is certainly a basic question with numerous reasons, I cannot seem to understand why it would be good idea to use throw when writing functions that validate.

For example if you take this simple username and password validation scenario, why would anyone want to use throw to help with the validation?

Does it just come down to coding style preference? Or is there a good reason one would opt for using throw for the return of this function?

enum ReturnMessages: String {
    case passed, failed, tooshort, nonumbers
}

func validateCredentials(username: String, password: String) -> ReturnMessages {
    guard (username.count >= 4 && password.count >= 4) else {return ReturnMessages.tooshort}
    guard (password.rangeOfCharacter(from: .decimalDigits) != nil) else {return ReturnMessages.nonumbers}
    
    return ReturnMessages.passed
}

validateCredentials(username: "jeff", password: "password")
1 Answers

Returning an enum value in this case is fine because the possibility to fail is quite high.

But consider that you have to use always a switch to distinguish the good from the bad path.

On the other hand in many cases the expected result is passed or some return value with a very low rate of errors. So isn’t it a better idea to return the good path directly and throw the bad paths.

The benefit is that you can continue your workflow without a runtime check good/bad.

Related