In Swift, what is the difference between access modifiers inside and out?

Swift offers 5 access modifiers: open , public , internal , fileprivate and private .

From what I know about these qualifiers (mainly from link and link_2 )

open means that classes and class members can be subclassed and redefined both inside and outside the defining module (target).

fileprivate restricts the use of an entity to its defining source file. It is mainly accessible by several classes in one file.

private restricts the use of an object in its declaration.

Now public and internal seems to me almost the same: -

public means that classes and class members can only be subclassed and redefined in the defining module (target).

internal allows you to use the object in the defining module (target). In addition, it turns out to be the default specifier if nothing is mentioned. Usually we will use internal access when defining applications or the internal structure of the framework.

Basically, how do public and domestic differ?

This is my first question here, so if I missed any details, please let me know. Thanks in advance.

+5
source share
2 answers

Everything that you marked as public can be used in your application and outside of your application (module). If you marked something as internal , which can only be used in your application (module). This is very useful when you are developing a library (framework), you can use the internal one to hide the structure of the library.
Public members A.swift and B.swift are available for C.swift and D.swift. The only limitation is that classes cannot be subclasses (they must be public ). - My answer base on @Keaz and @Alexander.

+2
source

From Access Control Guide :

Open access and public access to permission objects that will be used in any source file from their defining module, as well as in the source file from another module that imports the defining module . Usually you use open or open access when specifying the open interface on the framework. The difference between open and public access is described below.

Internal access allows an entity to be used in any source file from their defining module, but not in any source file outside this module . You typically use internal access when defining applications or the internal structure of the framework.

The difference in visibility for other modules.

EDIT to respond to @iCode comment:

You do not need all of them.

For the simplest small single-user application, it is enough to use the default internal .

If you need to do this correctly, you can add fileprivate / private accessors to hide some implementation.

If you are developing a large application and want to split the code into modules, or if you are developing a library, you will need to use public / open to create an inter-module interface.

+1
source

Source: https://habr.com/ru/post/1263054/


All Articles