我想创建一个继承自另一个类的类,该类位于不同的文件中。
例如:
Class1.swift
class Class1
{
protected var
//Do Stuff
}
Class2.swift
class Class2:Class1
{
//Do stuff
}
我怎样才能在 swift 中访问“ protected ”的变量/函数?
当我声明一个私有(private)变量/函数时,我只能在那个类中使用它。如果我使用“fileprivate”,我的其他类必须与 Class1
在同一个文件中。我想要做的是将我的类保存在单独的文件中,并使用 Xcode 中的组来了解哪个类属于哪个类别。
最佳答案
您必须为此使用 internal
,因为 Swift 不提供 protected
关键字(与许多其他编程语言不同)。 internal
是 fileprivate
和 public
之间唯一的访问修饰符:
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/