← Back to notes
TECHNICAL FIELD NOTES

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

Use a computed property on a Swift enumeration to return a different error message for each case.

Previously published at Original on the previous platform ↗ · First published

Archive note (2026-10-18): This article preserves the original 2016 Swift syntax and calling conventions, not current setup advice. Code has only been reformatted and typographic quotes normalized; samples were not executed.

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) {
    print(error.errorMsg)
}

displayError(errorFromApi)
// 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!

Original post at: http://www.igroomgrim.com/swift-trick-add-computed-property-enumeration/

Read more notes →