Wednesday, January 17, 2018

Swift Enums as Models

Enums have become more powerful in Swift. As powerful as they can be used as data models in Swift like Classes and Structures. (In Swift, all the 3 are Model objects)

Unlike in Objective C, Where only we can give int as raw value.

We can have String as raw values for Swift Enums. This may sound simple but can be a very useful feature. Let me explain with couple of scenarios.

We generally handle user login error scenarios and display respective alerts to the user based on the error from service. This is a very good use case off using enums with strings as raw values.

By taking LoginError Enum as Model for login error and keeping the respective message as raw value, It’s quite easy to display the respective error message to the user. And tomorrow, If we need to change any error message, all we need to touch is this LoginError Model file.

Sounds useful ?

Swift Enums can have methods in it which is not possible in Objective C.

Just like in classes, we can have methods in Enums. However, class methods are not allowed only static methods are allowed in Enums.

This is because, 

Only classes can have class methods and subclasses can override them.
class methods can be overridden but enums can’t be extended.

Class methods can be overridden but not Static Methods.

Let’s see how the same can be applied using enum static methods.

Last but not least, Enums are very useful for maintaining the state. They can have values associated with cases instead of just raw values.

Here, along with the case, We can store some values also for that state.

.loggedin(date: date)  - logged in date
.loggedout(date: date)  - logged out date
.loggingin(waitingTimeInsecs: Int) - Time taking for login

Hope this post is useful, Feel free to comment incase of any queries.