Validation of Fields in Swift

Asked

Viewed 522 times

3

How to validate fields using Swift? I intended to do with Exception, but I just searched and found that Swift has no Exceptions...

I’d like something like that:

void onCadastrar(dados){

    try {

        validarNome(dados.nome)
        validarSenha(dados.senha)
        ...
        etc

    } catch(MinhaException erro){

        //Alert da mensagem de erro

    }

}

This is possible on Swift?

  • 3

    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?

3 answers

6


In fact Swift does not have a Try catch, but rather has exceptions, as apple documentation.

As @Maniero mentioned, even in the languages that have the Try catch feature this should only be used in some situations.

Now to accomplish what you want I also point out the good old if.

Something like:

if dadosValidos() {
    enviarDados()
} else {
    exibeMensagemErro()
}

Now if you are making a Framework to be used by third parties, to capture you will have to check with if and then launch a fatalError() with the message, but this forces the application to stop.

0

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)
    }
}

0

can try using a type called Guard

guard let nome = dados.nome { print(erro) return }
resto do codigo

or if not, using if same

if let nome = dados.nome{ codigo}

in case, if it is possible to perform the assignment means that the field is not null

That’s kind of what you needed ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.