0

I am a newb to Swift, I am looking to create some nested namespaces, like so:

import Foundation 

public class Foo {
    class Moo {
        class Bar{}
    }
}

and then I can do:

var f = Foo.Moo.Bar()

do we not need to use the static keyword here? I don't understand why I don't need to do it like so:

import Foundation 

public class Foo {
    static class Moo {
        static class Bar{}
    }
}

var f = Foo.Moo.Bar()

can anyone explain why?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    I suspect you come from Java. If so, please see if [this answer](https://stackoverflow.com/a/26807041/77567) helps you. – rob mayoff Dec 06 '18 at 04:06

2 Answers2

0

Foo.Moo.Bar is just the name of the class. You're not accessing a particular instance of Foo or Moo when you do this:

var f = Foo.Moo.Bar()

You're just creating an instance of the Foo.Moo.Bar class.

Mike Taverne
  • 9,156
  • 2
  • 42
  • 58
0

can anyone explain why?

Can you explain why not? What would a static class even mean? How can a class be static? Maybe you come from a language where that keyword means something special in this context?

In any case, in Swift it wouldn't mean anything. The word static has just one very simple meaning in Swift: A type member, i.e. a property (var or let) or method (func) is either an instance member or a type member; to distinguish the latter case, we say static (or class). This is neither of those. It is, as you rightly say, merely a namespaced type.

matt
  • 515,959
  • 87
  • 875
  • 1,141