Submodules

Is it possible to create a series of modules and sub modules, e.g.

import Foo
import Foo.Bar

Today, attempting to name a target Foo.Bar seems to change the module name to Foo_Bar

Not like that with a dot. A module name must be a valid Swift identifier (or else put up with invalid characters needing to be replaced with _ in import statements.)

You can have a single library with multiple targets (modules), but it sounds like you’ve already figured that much out.

Swift doesn't support submodules. One way of mimicking nested modules/namespaces is using empty enums as namespaces.

How does this work within Apple frameworks, such as

import CoreImage.CIFilterBuiltins

That’s Objective-C.

Is there any advantage to using an enum for this rather than an empty struct?

If you use an empty enum you make it impossible to build an instance of that type: you can create an instance of an empty struct just calling its init, but you cannot do the same with an empty enum, as you don’t have any case to choose (this is also the implementation of Never)

3 Likes

You cannot create an instance of an enum without having an error thrown at you.

If you use enum as namespace, you can import enum Module.Submodule. But I don't think it looks any better. This syntax works for class & struct as well, so you can import struct Foundation.Data, for example.

Thanks for the reference, @Jessy!

For my package, I'm actually less interested in exposing multiple modules and more interested in having multiple modules during development and testing. To decrease code coupling and aid in API design, I want to have distinct components of the library I am working on be forced to depend on the public API of other components that they depend upon.

For people consuming the library, I still want a much simpler surface to import (plus more opportunities for the compiler to do code optimization).

1 Like
Terms of Service

Privacy Policy

Cookie Policy