Application development

Namespacing in Swift

Swift does not provide namespaces natively.


Therefore the language itself does not provide, like other languages, support for restricting constants and methods to a certain namespace.

Traditionally this feature on iOS and Mac is emulated to an extent, using a few letter prefix, in order to avoid clashing with other modules. Normally the prefix identifies the developer or the module.
E.g.: All old Objective C based “traditional” classes being named, for historical reasons, with a prefix “NS” (for Next Step).

This is still an available setting on XCode, which would prepend your chosen prefix to all the files you create.

However, in Swift, if all you want is allowing easy grouping of constants and methods under a name, you have a different solution:

You could define static methods and constants within a Class, a Struct or an Enum.

However, only Enums, without cases would prevent the public enum from being instantiated.

eg:

enum Math {

    static func square<T:FloatingPoint>(n: T) -> T {

        return n*n

    }

    static let pi = 3.14151697625

}

print (Math.square(n: 10.0),Math.pi)

Math, not having any case statement, can’t be instantiated, but its method and constant can be used in the code, and its name works as a surrogate of a namespace.

It is a kind of a trick, as it “misuses” a feature of the language to obtain something else, but it works and may give your code a little more readability, e.g.: allowing you to nicely group your constants by subject.

Of course you could use nesting in order to allow for more than a grouping level.

Leave a Reply

Your email address will not be published. Required fields are marked *