Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift 3, is there a difference between 'private class Foo' and 'fileprivate class Foo' in regards to member variables?

Tags:

swift

Specifically in regards to member variables, is there a difference between the following in Swift 3? In both cases, Foo is accessible by all code in that same file. Same thing with the implicitly-scoped 'laa' property, which seems to contradict the documentation.

If you define a type’s access level as private or file private, the default access level of its members will also be private or file private.

However, in both cases below, 'laa' is accessible from other classes in the same file implying that it is fileprivate, not private as the docs say the first one should be.

private class Foo
{
    var laa:String
}

fileprivate class Foo
{
    var laa:String
}
like image 639
Mark A. Donohoe Avatar asked Apr 19 '17 18:04

Mark A. Donohoe


1 Answers

As said in this Q&A – there's no difference in the access levels between a top-level private and fileprivate declaration. private simply means that it's accessible only in the enclosing scope1, and at the top-level – the file is that scope.

Regarding the documentation comment:

If you define a type’s access level as private or file private, the default access level of its members will also be private or file private.

I would say this is incorrect, or at the very least misleading in the case of private. The scope in which a given type's members are visible is by default the scope that the type declaration itself is visible in (with the exception of access levels higher than internal).

Therefore the scope in which a private type's members are accessible is by default the enclosing scope that defines that type. At the top level, that's the file.

It's probably simpler just to say that type members default to being internal. Being declared in a type with a lower access level than this (such as private or fileprivate) just prevents the members from being visible outside of these access levels (as it makes no sense to refer to a given type's member without being able to see the type itself).


1. Note that in Swift 4, as per SE-0169, extensions of a given type that are declared in the same source file as the type have the same access control scope as the scope of the type declaration. Therefore they can access private members of the type.

like image 142
Hamish Avatar answered Nov 27 '22 08:11

Hamish