Junior — Middle
What is the difference between the access modifiers 'fileprivate' and 'private' in Swift?
sobes.tech AI
Answer from AI
In Swift, access modifiers private and fileprivate restrict code visibility but differ in their scope:
-
privatelimits access to the same declaration (e.g., class, struct, or extension). Even within the same file, outside this declaration, access is denied. -
fileprivateallows access to the entire element within the same file. That is, all types and functions in one file can seefileprivateelements.
Example:
class MyClass {
private var privateValue = 1
fileprivate var fileprivateValue = 2
}
extension MyClass {
func test() {
print(privateValue) // Accessible, as in the same declaration
print(fileprivateValue) // Accessible
}
}
func outside() {
let obj = MyClass()
// print(obj.privateValue) // Error: private outside the class
print(obj.fileprivateValue) // Accessible, as in the same file
}
Thus, private is the most restrictive level, limited to the declaration, while fileprivate extends accessibility to the entire file.