enum ValidationError: Error {
case invalidInput
case missingInput
case alreadyInUse
}
extension ValidationError: LocalizedError {
var errorDescription: String? {
switch self {
case .invalidInput:
return "xxxxx"
case .missingInput:
return "The username cannot be empty"
case .alreadyInUse:
return "This username is already in use. Please try again"
}
}
class InputValidator {
func validateWithTypedThrow(_ input: String) throws(ValidationError) {
guard !input.isEmpty else { throw .missingInput }
guard input.count > 2 else { throw .invalidInput }
guard !existingUsernames.contains(input) else { throw .alreadyInUse }
}
}
// Event
Button("Validate") {
do throws(ValidationError) {
try validator.validateWithTypedThrow(username)
self.errorMessage = nil
self.successMessage = "Validation successful!"
} catch {
self.errorMessage = error.localizaedDescription
switch error {
case .invalidInput:
break // do something ex) call api
case .missingInput:
break // present alert
case .alreadyInUse:
break // do something
}
} /* catch let error as ValidationError {
} */
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme