How to use Namespaces in Swift?

后端 未结 8 1955
Happy的楠姐
Happy的楠姐 2020-11-28 01:53

The documentation only mentions nested types, but it\'s not clear if they can be used as namespaces. I haven\'t found any explicit mentioning of namespaces.

8条回答
  •  时光取名叫无心
    2020-11-28 02:36

    You can use extension to use the mentioned structs approach for namespacing without having to indent all of your code towards the right. I've been toying with this a bit and I'm not sure I'd go as far as creating Controllers and Views namespaces like in the example below, but it does illustrate how far it can go:

    Profiles.swift:

    // Define the namespaces
    struct Profiles {
      struct Views {}
      struct ViewControllers {}
    }
    

    Profiles/ViewControllers/Edit.swift

    // Define your new class within its namespace
    extension Profiles.ViewControllers {
      class Edit: UIViewController {}
    }
    
    // Extend your new class to avoid the extra whitespace on the left
    extension Profiles.ViewControllers.Edit {
      override func viewDidLoad() {
        // Do some stuff
      }
    }
    

    Profiles/Views/Edit.swift

    extension Profiles.Views {
      class Edit: UIView {}
    }
    
    extension Profiles.Views.Edit {
      override func drawRect(rect: CGRect) {
        // Do some stuff
      }
    }
    

    I haven't used this in an app since I haven't needed this level of separation yet but I think it's an interesting idea. This removes the need for even class suffixes such as the ubiquitous *ViewController suffix which is annoyingly long.

    However, it doesn't shorten anything when it's referenced such as in method parameters like this:

    class MyClass {
      func doSomethingWith(viewController: Profiles.ViewControllers.Edit) {
        // secret sauce
      }
    }
    

提交回复
热议问题