Swift offers 5 access modifiers: open
, public
, internal
, fileprivate
and private
.
Of what I know about these specifiers, (mainly from link & link_2)
open
means classes and class members can be subclassed and overridden both within and outside the defining module (target).
fileprivate
restricts the use of an entity to its defining source file. Basically accessible by multiple classes within a single file.
private
restricts the use of an entity to its enclosing declaration.
Now, public and internal seems pretty much the same to me :-
public
means classes and class members can only be subclassed and overridden within the defining module (target).
internal
enables an entity to be used within the defining module (target). Also, this happens to be the default specifier if nothing else is mentioned. We would typically use internal access when defining an app’s or a framework’s internal structure.
So basically how do public and internal differ?
This is my first Question here, so if I have missed out any details, please let me know. Thanks in advance.
Whatever you marked as public can be use within your app and outside of you app(module). If you marked something as internal that can only be used within your app(module). This is very helpful when your developing a library (framework) , you can use internal to hide library structure.
And Public members of A.swift and B.swift are available to C.swift and D.swift. The only restriction is that classes can't be subclassed (they would need to be open.)
- My answer base on @Keaz & @Alexander.
From Access Control manual:
Open access and public access enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use open or public access when specifying the public interface to a framework. The difference between open and public access is described below.
Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.
Difference is in visibility to other modules.
EDIT to answer @iCode comment:
You don't need all of them.
For simplest small single-dev application just using default internal
will be enough.
If you will need to do it right you may add fileprivate
/private
accessors to hide some implementation.
If you're developing large app and want to separate code into modules, or if you're developing library you will need to use public
/open
to create inter-module interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With