Access Controls

Swift has three levels of access controls:

  1. Public access enables entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use public access when specifying the public interface to a framework.

  2. Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.

  3. Private access restricts the use of an entity to its own defining source file. Use private access to hide the implementation details of a specific piece of functionality.

By default, every function and variable is internal. If you want to change that, use the private or public keyword in front of every single method and variable:

 public func myPublicFunc() {
 
 }
 
 func myInternalFunc() {
 
 }
 
 private func myPrivateFunc() {
 
 }
 
 private func myOtherPrivateFunc() {
 
 }

Coming from Ruby, I prefer to put all my private functions at the bottom of my class, separated by a landmark:

 class MyFunClass {
 
  func myInternalFunc() {
 
  }
 
  // MARK: Private Helper Methods
 
  private func myPrivateFunc() {
 
  }
 
  private func myOtherPrivateFunc() {
 
  }
 }

Hopefully, future releases of Swift will include an option to use one private keyword to indicate that all methods below it are private, similar to how access controls work in other programming languages.