In depth understanding of access control keywords in Swift

  • 2020-05-19 06:02:15
  • OfStack

preface

Before Swift3.0, there were three access control keywords: private, internal, and public. After swift3, two access control keywords were added: fileprivate and open. They can be viewed as further subdivisions of private and public. The following are the differences between the modifiers and the access ordering.

The difference between the individual modifiers

private

The swift3.0 private access level modifies properties or methods that can only be accessed in the current class.


class A {
 private func test() {
  print("this is private function!")
 }
}

class B: A {
 func show() {
  test()
 }
}

The above code will compile successfully before swift3.0, but will fail in swift3.0, indicating that the test() method is not available in class B.

fileprivate

fileprivate is the new permission modifier after Swift3.0. The properties or methods modified by fileprivate access level can be accessed in the current Swift source file. (if you change private to fileprivate in the example above, you won't get an error).

internal

internal is the default access level and may not be written by default. The attributes or methods modified by the internal access level are accessible throughout the module where the source code resides. If it is framework or library code, it can be accessed throughout the framework, but not if it is referenced by external code. If it's the App code, it's also within the entire App code, and it's also within the entire App code.

public

It can be accessed by anyone. However, other module can not be override and inheritance, but in module can be override and inheritance.

open

open is a new permission keyword after swift 3.0 and can be used by anyone, including override and inheritance.

Modifier access sort

The order of access control from high to low is as follows

open > public > interal > fileprivate > private

conclusion


Related articles: