DEV Community

loading...

Namespaces in Swift

tom0pearson profile image Tom Pearson ・2 min read

Namespaces in their simplest form are a way to group related areas of code. They make one of the hardest problems in programming, naming things, easier. They exist in a lot of other languages but not natively in Swift.

Microsoft's C++ documentation says:

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

The Problem

If you're working on a large codebase then you probably name classes specifically enough so you won't get them confused with other areas of the codebase. Unfortunately to achieve this we have to make the trade off of longer class names to get this specificity. Also as we add more and more classes the global namespace gets more polluted, meaning that you end up with an information overload when trying to use autocomplete.

For example you'd probably make classes like LoginViewController or ContactsDataSource. This can be taken to more of an extreme as you get into very specific workflows in a large codebase.

 The Solution

A nice, swifty way to solve this is to use an empty enum to create a gateway into the specific workflow and implement all specific classes inside extensions on that enum. You can then access these classes using the dot syntax. So instead of the examples above you would have Login.ViewController and Contacts.DataSource.

This also helps you organise code into logical groups - you know all the code related to the login flow will be under the Login namespace.

Implementation in Code

Making the namespace is just making an empty enum:

enum Login {}

Then the classes are implemented as extensions to that enum in a new file, in this case probably called Login+ViewController.swift:

extension Login {
    class ViewController: UIViewController { ... }
}

We use an enum instead of a struct because you can't instantiate an empty enum, so it can purely be used for accessing other classes without confusion of what its purpose is.

References

Microsoft Namespace Documentation

Some speaker at a Meetup who said that he did this

Discussion (0)

pic
Editor guide