Please do NOT use View tags in your Swift project


Steven Curtis
4 min readOct 26, 2021


View Tags. Aren’t they great?

Photo by Paul Skorupskas on Unsplash

The code for this article is stored right HERE

Never use them

The compiler does not enforce the use of unique tags. Worse, some programmers use tags in order to reference arrays of data in their code.

You’re doing it wrong

You can add tags to views in the storyboard

or you can do it programatically

let view = UIView()
view.tag = 0

now (for this example’s sake) both have a tag of 0. One reason for choosing 0 for the example is that 0 is set in the storyboard if you do not choose to set any particular tag. That said, it is for this example only.

Discovering the tag in views.

This can be done programatically, and for each of these we print out the tag.

for subView in view.subviews {

Now in my example App I’ve included two UIView on the storyboard. Now guess the output — what do you think will happen?


Both of the subviews in this case have the same tag. 0. We are relying on our programmer (or perhaps ourselves) to be good citizens and tag views with a unique identifier.

Using tags to store data

Remember that some programmers are using tags to store data in their code? You might have an array

let data = ["A", "B", "C", "D"]

Then use the tag to reference to the data array when we use a gesture to detect touches on the object

let gesture = UITapGestureRecognizer(target: self, action: #selector(logToConsole))firstView.addGestureRecognizer(gesture)

which then references the following function

@objc func logToConsole(_ sender: UITapGestureRecognizer){
print("The sender data is : \(data[sender.view?.tag])")}

provided we can think to zero-index the tags when we give them those tags.

The problems



Recommended from Medium


See more recommendations