How to use Namespaces in Swift?

I would describe Swift’s namespacing as aspirational; it’s been given a lot of advertising that doesn’t correspond to any meaningful reality on the ground.

For example, the WWDC videos state that if a framework you’re importing has a class MyClass and your code has a class MyClass, those names do not conflict because “name mangling” gives them different internal names. In reality, however, they do conflict, in the sense that your own code’s MyClass wins, and you can’t specify “No no, I mean the MyClass in the framework” — saying TheFramework.MyClass doesn’t work (the compiler knows what you mean, but it says it can’t find such a class in the framework).

My experience is that Swift therefore is not namespaced in the slightest. In turning one of my apps from Objective-C to Swift, I created an embedded framework because it was so easy and cool to do. Importing the framework, however, imports all the Swift stuff in the framework – so presto, once again there is just one namespace and it’s global. And there are no Swift headers so you can’t hide any names.

EDIT: In seed 3, this feature is now starting to come online, in the following sense: if your main code contains MyClass and your framework MyFramework contains MyClass, the former overshadows the latter by default, but you can reach the one in the framework by using the syntax MyFramework.MyClass. Thus we do in fact have the rudiments of a distinct namespace!

EDIT 2: In seed 4, we now have access controls! Plus, in one of my apps I have an embedded framework and sure enough, everything was hidden by default and I had to expose all the bits of the public API explicitly. This is a big improvement.

Leave a Comment