Secure Access Level in Swift

How to make a protected (e.g. ruby) variable or function in Swift? I know that Swift has only 3 levels, but nevertheless it is possible?

Access levels

Swift provides three different access levels for objects inside your code. These access levels relate to the source file in which the entity is defined, and also relative to the module that the source file belongs to.

  • Open access allows entities to 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 access when specifying the public interface on the framework.
  • Internal access allows an entity to be used in any source file from their module definition, but not in any source file outside this module. You usually use internal access when defining applications or internal frameworks.
  • Private access restricts the use of an object to its own defining source file. Use private access to hide implementation details of a particular piece of functionality.

Public access is the highest (least restrictive) access level and private access is the lowest (or most restrictive) access level

Currently, I see only one solution: write a parent class with a private modifier and a child class in one file, but this will be painful.

+6
source share
4 answers

In Ruby's point of view, this can be important. However, nothing is useless in Swift, and it is not a question of language.

Swift is primarily module based when it comes to access levels. It even has public private(set) variables that are very needed in Objective-C (invokes the template).

+3
source

Swift prefers not to use protected . You can read the reasons here. Access control and protection.

In contrast, protection protects access with inheritance by adding a completely new control axis to the cause. It actually offers no real protection, since a subclass can always expose a “protected” API through a new public method or property. It also does not offer additional optimization options, as new overrides can come from anywhere. And its overly restrictive - it allows subclasses, but not any subclass helpers, to access anything.

+4
source

There is no protected equivalent in Swift, where only subclasses have access to the method. Personally, I don't miss him.

In Swift (like Objective-C) much less attention is paid to a subclass than to other languages. If you find that you have a set of methods that you want to protect, it is probably best to separate them as a delegate.

+3
source

Swift 3.0 does not protect the protective modifier. In our sdk we use an internal (specified) modifier that approves the installation operation only in the sdk project.

 private var _authorized : Bool = false public internal(set) var authorized : Bool { get { return _authorized; } set { _authorized = newValue } } 
+1
source

All Articles