Fields Validation in Swift

Posted on

Question :

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

I would like something like this:

void onCadastrar(dados){

    try {


    } catch(MinhaException erro){

        //Alert da mensagem de erro



Is this possible in SWift?


Answer :

Actually Swift does not have a try catch, but rather has exceptions, as Apple documentation .

As @bigown mentioned, even in languages that have try catch this should only be used in some situations.

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

Something like:

if dadosValidos() {
} else {

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

You can try to use a type called guard

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

or if not, using itself

if let nome = dados.nome{ codigo}

In case, if it is possible to assign it means that the field is not null

Was that what you needed?


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 {


Leave a Reply

Your email address will not be published. Required fields are marked *