1

Is putting your class inside a struct an acceptable way to namespace your class in Swift? I did not see any mention of nested struct or struct-class in the programming guide.

struct TestNamespace {
    class Test {

    }
}
Boon
  • 40,656
  • 60
  • 209
  • 315
  • "Acceptable" is a loosely define term and subject to debates. See: http://stackoverflow.com/q/24002821/how-do-you-use-namespaces-in-swift –  Sep 03 '14 at 19:45
  • 2
    Why do you want to namespace your class? Isn't the module namespace enough? A real example might help us figure out if there may be a better solution. – Matt Gibson Sep 04 '14 at 06:23
  • Using dynamic frameworks (iOS 8+) all classes belong to their module namespace. – redent84 Mar 17 '16 at 08:43

1 Answers1

0

I'd be (even more) happy with namespaces in Swift, because they help organize the code more granularly. If you're experimenting with using struct as a namespace, consider disabling its construction:

struct PseudoNamespace {

    private init() {}

    //...

}

Using struct has an advantage over using class: structs does not support inheritance and with classes it needs using final modifier.

One significant disadvantage of this emulation is that there is no way no "import" such a namespace (like import PseudoNamespace.*, etc.), because Swift allows importing modules, but not structs.

werediver
  • 4,667
  • 1
  • 29
  • 49
  • No way to import because of private init or struct? – Boon Mar 16 '16 at 20:27
  • Private `init` only denies construction. Swift allows importing _modules_, but `struct` is not a module, so the language does not allow to import it. You'll always need to type the struct name to address the nested items, like `PseudoNamespace.NestedClass`. – werediver Mar 17 '16 at 07:45