Input Validation in Swift

darthpelo
2 min readJul 31, 2019

--

In 8 years as mobile developer input validation was always “something” to implement on a ViewController during/after the user enters a value in a text field and then store inside a model (username, email address, home address etc.). In my mind, the input is validated, and I never thought that every time I update the same property of the model, for example after I parse a JSON or using input from a function, I need to validate the input again. Seems like that we don’t trust a user but blindly trust any inputs from machines.
Unfortunately, humankind is involved always and bugs with them.

A simple solution to avoid this mindset is to implement automatically the input validation every time the property is written, so you never think about since the input validation happens behind the scenes.

Input as a Type

Thing your input, like an email address, as a Type. Every time you create a new instance of it using a String, as any others Types, you expect that the compiler or a run-time check, ensure that your new instance is correct. In this way, every time a module needs to create an email instance, you never forget to validate it, since the validation is part of the email itself.

Something like that:

The Email Type has a constructor that check if the String passed as value for the initialization is valid; otherwise, it throws an error.

Property Wrapper

Less powerful than the first solution, Property Wrapper introduced with Swift 5.1 can help you make Input Validation automatically.

In this example we created the wrapper @EmailValidated that dosen’t return any error if the String is not a valid email, but only sets it as empty string.

--

--

darthpelo

Software Engineer & Senior iOS developer at @mobiquityinc NL. Craft Beer addict. Il caso non esiste. Il caos sì /The case does not exist. The chaos exists.