swift - 如何在 swift 中声明一个 'protected' 变量

标签 swift class swift3 encapsulation

我想创建一个继承自另一个类的类,该类位于不同的文件中。

例如:

Class1.swift

class Class1
{
    protected var 
    //Do Stuff
}

Class2.swift

class Class2:Class1
{
    //Do stuff
}

我怎样才能在 swift 中访问“ protected ”的变量/函数?

当我声明一个私有(private)变量/函数时,我只能在那个类中使用它。如果我使用“fileprivate”,我的其他类必须与 Class1 在同一个文件中。我想要做的是将我的类保存在单独的文件中,并使用 Xcode 中的组来了解哪个类属于哪个类别。

最佳答案

您必须为此使用 internal,因为 Swift 不提供 protected 关键字(与许多其他编程语言不同)。 internalfileprivatepublic 之间唯一的访问修饰符:

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.

有一个blog post这更多地解释了为什么语言设计者选择不提供 protected 关键字(或任何等效的关键字)。

一些原因是这样的

It doesn’t actually offer any real protection, since a subclass can always expose “protected” API through a new public method or property.

还有 protected 会在扩展​​方面引起问题,因为不清楚扩展是否也应该访问 protected 属性.

关于swift - 如何在 swift 中声明一个 'protected' 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41764977/

相关文章:

swift - OSLogPrivacy : what's the difference between . 私有(private)和敏感?

java - 编译错误java.lang.nullpointerException

c# - 如果类继承多次可以慢一些吗?

ios - 通过 Alamofire 上传图片失败

ios - UIKeyboardTaskQueue 只能从主线程调用

ios - 当我们使用VIPER架构时如何创建常量?

c++ - 通过名称创建对象

swift3 - 如何快速计算 uicollectionview 的行数

ios - 带 header 的Alamofire 4分段上传

iOS自定义 View ,更改UILabel textColor/isHidden不起作用