Practical Uses of Swift Enum

Ever since Moya helped me understand some of the hidden power in Swift enums, I have found some other practical examples where enums can help provide a more readable and strongly typed alternative when working with UIKit and 3rd Party APIs.

Take Analytics for example, most analytics libraries provide a singleton which you initialize in your App Delegate and sprinkle references to throughout your application. Most events sent are specified via a String as an argument to the singleton.

Mixpanel.sharedInstance.track(“Log in”)

At first glance there are a few issues, first the String constant should be externalized, as well as now I have a reference to Mixpanel all over my app. If I want to switch providers, or add other tracking info, such as breadcrumbs for crash reporting I have to add an additional line, wherever I’m doing analytics.

Mixpanel.sharedInstance.track(“Log in”)
CLSLogv(“Log in”)

A Swift Enum can not only provide encapsulation for these tasks but also provides a central place to look when asked the question: “Do we have an event for xyz?”

Our enum can look something like this.

enum Tracking : String {
case Login = “Log In”
}
extension Tracking {

func send() {
Mixpanel.sharedInstance.track(self.rawValue)
CLSLogv(self.rawValue)
}
}

Using it would look like this, much cleaner

func login() {
Tracking.Login.send()
}

Some other usages of Swift Enums that I have found useful are working with NSUserDefaults specifically for Boolean settings, and naming Sections and Rows for use with UITableView and UICollectionView.

Software Engineer/Architect

Software Engineer/Architect