Did you find this helpful? Why not support me to bring you even more content.
Click here to Buy Me a Coffee and say Thanks!

DISCLAIMER: This post is older than one year and maybe out of date.

Namespacing with Swift

Name spaces are a way to group items together without fear of them treading on the toes of other items. Let’s take a look at this concept using Swift.

Swift does not have a namespace keyword like some other languages, but we can implement the ideas using either a struct or enumeration to encapsulate the items into that namespace.

One common use can be to group together constants, in the example below I have grouped my name, web site and twitter name into an enum called myDetails. This acts like a namespace when it comes to accessing the properties.

Now because I used an enum here, you cannot instantiate it, unlike a struct. You can only access the data. Perfect for constants or say API functionality that you want to expose.

You can take this further of course, what if we add an enum inside the enum

The other advantage is that I can now have the same property names somewhere else in my application without having to worry about conflicts.

The Wrap

So there you have it, a simple example of name spacing data using enums. Grouping data into logical name spaces can be a good way to move data around easier when you need to without having to go find it.