gpt4 book ai didi

swift - Swift 扩展的访问控制

转载 作者:IT王子 更新时间:2023-10-29 05:50:11 26 4
gpt4 key购买 nike

Swift 编程语言对扩展的访问控制有这样的说法:

You can extend a class, structure, or enumeration in any access context in which the class, structure, or enumeration is available. Any type members added in an extension have the same default access level as type members declared in the original type being extended. If you extend a public or internal type, any new type members you add will have a default access level of internal. If you extend a private type, any new type members you add will have a default access level of private.

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

上面的说法我不是很理解。是否在说以下内容:

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 "" }
}

最佳答案

你的理解几乎是正确的。

放置场景 3 的更有趣的方式是

extension Test {
// The extension has access control internal, because of what the docs say:
//
// > If you extend a public or internal type, any new type members you add
// > will have a default access level of internal.
//
// Despite the extension being internal, this member is private because it's
// declared explicitly here.
private var prop2: String { return "" }
}

还有

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

您可能还会发现有趣的是,如果您的类、结构或枚举是 internal,您将无法定义 public 扩展。这同样适用于 private 类、结构或枚举,您不能为其定义 publicinternal 扩展。

关于swift - Swift 扩展的访问控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33925840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com