Swift Trick : How to add a computed property to enumeration.

I was found the useful trick in Swift. We create Enumeration for defines a common type for a group of related values. The power of Swift we can add a computed property to enumeration.

We can create simply computed property as shown in the following code :

enum ApiError {
case NoInternetConnection
case AuthenticationFail
case ResponseTimeOut
var errorMsg: String {
switch self {
case .NoInternetConnection:
return “Internet connection has problem!”

case .AuthenticationFail:
return “Error has Authentication fail!”

case .ResponseTimeOut:
return “Too longggggg :P”

Then our enumeration can retrieve errorMsg value as String type.

In code demonstrates how to use them:

let errorFromApi = ApiError.NoInternetConnection
func displayError(error: ApiError) {
// The result will display "Internet connection has problem!"

Nice! Enumerations in Swift are a lot more powerful.
Hopefully, I think you will get some a good trick from Enumerations.
Finally, what’s your opinion about Enumerations?
You can leave your comment below. Let’s share idea!

Thank nice image from

Infinite Scroll with custom UIPageViewController with filter data
How to make tableviewcell animation using Swift
CLLocationManager Singleton in Swift