Although other alternatives are recommended it is possible to do this way yes, I’ve asked myself that same question using this same field validation case and solved as follows:
first you can make an Enum to list all possible error that will be returned
enum ValidatingError: Error {
case invalidName
case invalidPassword
}
Do an extension to specify the return of each error
extension ValidatingError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidName:
return NSLocalizedString("ERRO no nome", comment: "Coloque um nome com mais de 3 letras")
case .invalidPassword:
return NSLocalizedString("Erro na senha", comment: "A senha deve conter 6 ou mais caracteres")
}
}
}
Create the validation functions
func valida(_ nome: String) throws {
if nome.count <= 3{
throw ValidatingError.invalidName
}
}
func valida(_ senha: String) throws {
if senha.count <= 6{
throw ValidatingError.invalidPassword
}
}
And to call the way you specified just call the methods in and one of the catch
func onCadastrar(dados: Dados){
do {
try valida(dados.nome)
try valida(dados.senha)
} catch {
print(error)
}
}
I was glad to hear that, then people stop abusing the resource that should be used only in exceptional situations. The problem is that people will probably abuse something else. I don’t know about Swift’s specific resources but what happened to the good old
if
?– Maniero