How to declare a 'protected' variable in swift
I want to create a class that inherits from another class, which is in a different file.
For example:
Class1.swift
class Class1
{
protected var
//Do Stuff
}
Class2.swift
class Class2:Class1
{
//Do stuff
}
How would I be able to have access to a 'protected' variable/function in swift?
When I declare a private variable/function, I can only use it in that class. If I use 'fileprivate', my other class HAS to be in the same file as Class1
. What I want to do is keep my classes in separate files and use the Groups from within Xcode to know what class belongs with which category.
You would have to use internal
for that as Swift doesn't offer a protected
keyword (unlike many other programming languages). internal
is the only access modifier between fileprivate
and 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.
There is a blog post that explains a little bit more about why the language designers chose not to offer a protected
keyword (or anything equivalent).
Some of the reasons being that
It doesn’t actually offer any real protection, since a subclass can always expose “protected” API through a new public method or property.
and also the fact that protected
would cause problems when it comes to extensions, as it wouldn't be clear whether extensions should also have access to protected
properties or not.
Even if Swift doesn't provide protected
access, still we can achieve similar access by using fileprivate
access control.
Only thing we need to keep in mind that we need to declare all the children in same file as parent declared in.
Animal.swift
import Foundation
class Animal {
fileprivate var protectedVar: Int = 0
}
class Dog: Animal {
func doSomething() {
protectedVar = 1
}
}
OtherFile.swift
let dog = Dog()
dog.doSomething()
Use an underscore for such protected variables :/
That's about it ...
class RawDisplayThing {
var _fraction: CGFloat = 0 {
didSet { ... }
}
class FlightMap: RawDisplayThing() {
var currentPosition() {
...
_fraction =
...
}
}
Everyone has to "just agree" that only the concept class can use the "_" variables and functions.
At least, it's then relatively easy to search globally on each "_" item and ensure it only used by the superclasses.
Alternately, prepend say "local", "display", or possibly the name of the class (or whatever makes sense to your team) to such concepts.
class RawDisplayThing {
var rawDisplayFraction: ...
var rawDisplayTrigger: ...
var rawDisplayConvolution: ...
etc etc. Maybe it helps :/