An Enum Based Approach to Namespaces

Reviving this as well lol, right there with you @David_Catmull

I am always using caseless enums as a way to organize my constants, inside of my types... ex:

class MyView: UIView {}

// MARK: Constants

extension MyView {
    enum Layout {
        enum Label {
            static let maxLines = 3
        }

        enum Image {
            static let margin = 5
        }
    }

    enum Style {
        static let background: UIColor = .white

        enum Image {
            static let background: UIColor = .purple
        }
    }
}

I use a lot of nesting, since it makes it really nice on the calling side where each context level is its own namespace, ex calling Layout.Image.margin inside of MyView... and you can use the same identifiers, just in different contexts, ex calling Style.background or Style.Image.background


After browsing different discussions in these forums about submodules and namespaces, I don't think the idea of a submodule really satisfies my use case... from my understanding of the Namespaces × submodules proposal, submodules can be nested within each other, sure... but they can't be nested within types... and I don't want to have to define a MyViewConstants submodule outside of MyView just to be able to define constants, for these reasons:

  • Naming conflicts
  • MyViewConstants should never be more visible than MyView -- which could happen if they were both top level types

What I would like to see is a namespace type that is non-instantiable, non-returnable, non-extendable, can be nested inside of other types, and where you don't need to mark static on everything... purely for the intention of better organization and code readability.

imo that outweighs the argument for not cluttering Swift with more keywords. I've also seen an argument in the forums that caseless enums are an established pattern that people are used to, but in my experience it's usually a pretty opinionated debate about struct with a private initializer vs caseless enum... since it's considered an anti-pattern to what an enum should really be.

2 Likes