Use Enums for Tags

maeganwilson_

Maegan Wilson

Posted on May 14, 2020

Use Enums for Tags

This article assumes you know what an Enum or Enumeration in Swift is, and will explain why they are a perfect use case for tags in iOS and macOS development. If you want to read more about Enums, the Swift website is a great resource!

What are tags?

A tag is an Int that is assigned in a view. If you create a new iOS app in Xcode that is a Tabbed app, you'll notice that the 2 tab views have a .tag() associated with each view. In the gist below, you can see that on lines 16 and 25.

If you have a lot of tabs in this view, then you might get confused about which tag number is associate with which tab. Enums can help make these tags more descriptive and more readable.

How do Enums help?

Enums have cases that are labeled and can conform to the Hashable protocol, which is needed for tags in SwiftUI.

An example of an Enum for views in a todo app can look like this

When declaring the enum, we need to make sure that it conforms to the Hashable protocol. We don't need to do anything else besides adopt it since there are no associated values with the cases. If there were associated values, then we would need to make sure those values are conforming to the protocol.

Those enum cases in the gist above are a lot more readable than the numbers. We know from a glance what view will be taken by pressing that tab.

How to implement the Enum in the app

Now, I am going to implement Tabs into the SwiftUI app created earlier. After declaring the enum in ContentView.swift, I need to change the State to be the inbox view, so the value of state needs to be Tabs.inbox. Next, I need to change the tags values to Tabs.inbox, Tabs.projects, and Tabs.settings. The gist below shows the final code of the project.

Line 4 shows the new State assignment and lines 22, 28, and 40 show the new tag values.

Now, it's a bit easier to read which tab is assigned to each view.

The completed project can be cloned from GitLab.


If you enjoy my posts, streams, and apps, consider encouraging my efforts.

💖 💪 🙅 🚩
maeganwilson_
Maegan Wilson

Posted on May 14, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related