Errors Validation In Swift!

Yosef Elbosaty
3 min readJun 4, 2022

--

Boring errors validation? Not anymore.

It was always boring validation errors while coding but now it is much pretty easier.

let’s say you are trying to run a login API service that takes two parameters maybe phone and password, What would you do?

As usual, you will check if the phone text field is empty or has fewer characters than you need and you will do the same for the password.

It will be something like that:

But it is a tedious way, isn’t it?

So!

We won't use it anymore, let’s see how to validate errors in a much pretty easier way.

We will make an enum let us name it “ValidationErrors” of type Error, We will write our validation cases, In our case, it will be:

  1. emptyPhoneNumber
  2. shortPhoneNumber
  3. emptyPassword
  4. shortPassword

Now, We will make an extension of our enum “ValidationErrors”, It will conform to LocalizedError protocol and we will declare a computed property of type String, let’s call it “errorDescription” and we will switch our “ValidationErrors” enum cases and in every case, we will return what we want to print or display in an alert.

It will be something like that:

Now, let’s go to the main and magical part of our article.

We will declare a struct let’s call it Validation, Here we will declare two functions as our validation case needs one for validating the phone number and the second one for validating the password which will throw an error in case it doesn’t match our validation conditions.

It will be like that:

Those functions take our text as input and validate it and if it doesn’t match our validation conditions it will throw an error or return the correct value if everything is right.

How to use it? let’s see:

Aaaaand 🪄 that's it.

Imagine having tens of validation cases it will cost you time and be very tedious to validate it all, But in my opinion, this way, it will be easier and will save you much more time.

I hope this article was useful … Thanks for reading.

--

--