gpt4 book ai didi

swift - Swift 中 protected 访问级别

转载 作者:IT王子 更新时间:2023-10-29 05:36:07 24 4
gpt4 key购买 nike

如何在 Swift 中创建 protected (如在 ruby​​ 中)变量或函数?我知道 Swift 只有 3 个级别,但这有可能吗?

访问级别

Swift provides three different access levels for entities within your code. These access levels are relative to the source file in which an entity is defined, and also relative to the module that source file belongs to.

  • Public access enables entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use public access when specifying the public interface to a framework.
  • Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.
  • Private access restricts the use of an entity to its own defining source file. Use private access to hide the implementation details of a specific piece of functionality.

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

目前我只看到一种解决方案——在单个文件中编写带有私有(private)修饰符的父类和子类,但这有点痛苦。

最佳答案

Swift 不喜欢使用 protected。您可以在此处阅读原因 Access Control and protected

In contrast, protected conflates access with inheritance, adding an entirely new control axis to reason about. It doesn’t actually offer any real protection, since a subclass can always expose “protected” API through a new public method or property. It doesn’t offer additional optimization opportunities either, since new overrides can come from anywhere. And it’s unnecessarily restrictive — it allows subclasses, but not any of the subclass’s helpers, to access something.

关于swift - Swift 中 protected 访问级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32603179/

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