How do access control levels (open, public, internal, fileprivate, private) work?

In Swift, access control levels determine the visibility of entities such as classes, structs, properties, and methods. The five levels of access control in Swift are:

  • open: The entity can be accessed and subclassed outside the defining module.
  • public: The entity can be accessed from any source file in the defining module and from outside the module, but it cannot be subclassed outside the module.
  • internal: This level is the default. It allows access from any source file within the same module but not from outside.
  • fileprivate: The entity is accessible only within the same source file.
  • private: The entity is accessible only within the enclosing declaration and extensions of that declaration.

Here's a Swift code example demonstrating the different access levels:

// Open access open class OpenClass { open func openMethod() {} } // Public access public class PublicClass { public func publicMethod() {} } // Internal access (default) class InternalClass { func internalMethod() {} } // Fileprivate access fileprivate class FilePrivateClass { func filePrivateMethod() {} } // Private access private class PrivateClass { func privateMethod() {} }

Swift access control levels open public internal fileprivate private Swift programming