Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use File-Private Access Control in Swift
Written by Team Kodeco

File-private access control in Swift allows you to limit the scope of variables, constants, properties and functions to the file they are defined in. This means that they can only be accessed within the same file and not from other files within the same module.

This is useful when you have a group of related functions or properties that you want to keep together in a single file, but you don’t want them to be accessible to other parts of your codebase.

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

class MyClass {
  fileprivate var myFilePrivateProperty = "I'm file private"
  fileprivate func myFilePrivateMethod() {
    print("I'm a file-private method")
  }
}

In this example, myFilePrivateProperty and myFilePrivateMethod can be accessed from within the MyClass class, as well as any extension of MyClass within the same source file. If you try to access them from outside the source file, you’ll get a compile-time error.

It’s important to note that file-private access control is different from private access control which only allows access within the same scope (class, struct, or enumeration).

© 2024 Kodeco Inc.