Access Control for Quick Extensions

A fast programming language talks about access control for extensions:

You can extend a class, structure, or enumeration in any access context in which a class, structure, or enumeration is available. Any type members added to the extension have the same default access level, because type members declared in the source type are expanded. If you are distributing a public or internal type, any new type members that you add will have a default access level for internal use. If you are a type, any new type members you add will have a default private access level.

Alternatively, you can mark the extension with an explicit access level modifier (for example, private extension) to set a new default access level for all members defined in the extension. This new default value can still be overridden in the extension for an individual type of member.

I do not fully understand the above. He says the following:

public struct Test { }

extension Test {
  // 1. This will be default to internal because Test is public?
  var prop: String { return "" }
}

public extension Test {
  // 2. This will have access level of public because extension is marked public?
  var prop2: String { return "" }

extension Test {
  // 3. Is this the same as the above public extension example?
  public var prop2: String { return "" }
}
+4
source share
1 answer

Your understanding is correct.

Note: public Test { }must bepublic struct Test { }

A more interesting way to post your scenario 3 would be

extension Test {
  // The exension has the same access control of Test, but this member is private
  private var prop2: String { return "" }
}

as well as

internal extension Test {
  // The compiler will throw a waning here, why would you define something public in an internal extension?
  public var prop2: String { return "" }
}

, , , internal, public. private, , public internal.

+4

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


All Articles