Although other alternatives are recommended, it is possible to do this yes, I already asked myself the same question using this same field validation case and I solved it as follows:
You can first make an enum to list all possible error types that will be returned
enum ValidatingError: Error {
case invalidName
case invalidPassword
}
Make 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 is to just call the methods inside and one of the catch
func onCadastrar(dados: Dados){
do {
try valida(dados.nome)
try valida(dados.senha)
} catch {
print(error)
}
}