Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Private Access Control in Swift
Written by Team Kodeco

The private access level is the most restrictive level of access control in Swift.

Classes, structures and enumerations that are defined as private can only be accessed from within the source file where they are defined. Properties and methods that are defined as private can only be accessed from within the class, structure or enumeration where they are defined.

Here’s an example of a class that has a private property and a private method:

class MyClass {
  private var myPrivateProperty = "I'm private"
  private func myPrivateMethod() {
    print("I'm a private method")
  }
}

In this example, myPrivateProperty and myPrivateMethod can only be accessed from within MyClass. If you try to access them from outside the class, you’ll get a compile-time error.

It’s important to note that if a property or method is marked as private, it can still be overridden by a subclass, but the subclass cannot access the superclass’s implementation.

© 2024 Kodeco Inc.