In Swift, both private
and fileprivate
are access control modifiers used to restrict access to properties, methods, types, and other code elements. They differ in the scope of access they provide:
private
: This is the most restrictive access level. A private
element can only be accessed from within the enclosing declaration (like a struct, class, or enum) and its extensions, but only if those extensions are defined in the same source file. In other words, something marked as private
is hidden from anything outside of its definition block, even within the same file if it’s not part of an extension in the same file.
fileprivate
: This access level allows elements to be accessed from anywhere within the same source file, regardless of the enclosing declaration. So, a fileprivate
element can be used by other parts of the code in the same file, even if they are outside of the specific type or block where it was declared.
Here’s a table summarizing the key difference:
Access Level | Accessible From |
---|---|
private |
Enclosing declaration and extensions in the same file |
fileprivate |
Entire source file |
Choosing Between private
and fileprivate
private
when you want to hide an element completely within its enclosing declaration and only allow access through its public interface. This promotes encapsulation and improves code maintainability.fileprivate
when you have helper methods or properties that are useful within the same file but don’t need to be exposed publicly. This can help reduce code duplication and improve organization within a single file.In general, private
is the more commonly used access level as it provides the strictest level of access control. You should only use fileprivate
when you have a specific reason to allow access from other parts of the same file.