How to declare a 'protected' variable in swift
Solution 1
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.
Solution 2
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()
Solution 3
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 :/
Solution 4
If you dont want to have both classes belonging to the same file, here is what you can do:
class Parent {
internal private(set) var myProtectedBoolean = false
}
Then on the child class:
class Child: Parent {
private var _myProtectedBoolean: Bool = false;
override var myProtectedBoolean: Bool {
get { return _myProtectedBoolean }
set { _myProtectedBoolean = newValue }
}
}
Related videos on Youtube
iProgram
Updated on July 09, 2022Comments
-
iProgram almost 2 years
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.-
Sulthan over 7 yearsPossible duplicate of Does Swift have access modifiers?
-
iProgram over 7 years@Sulthan I saw that post becase it did not say anything about 'protected'. This could have been somthing that was added in a later version of swift, or be accsessed in a diffrent way.
-
Sulthan over 7 yearsA group in Xcode has nothing to do with compilation or with the language itself. It's just a way to logically group files in your project, the same as folders in your file system. If you want to separate implementation, you will have to use modules, that is, targets in the project. And then use
internal
. -
Sulthan over 7 yearsThe post I linked is updated for Swift 3.
-
iProgram over 7 years@I know about the groups. I like having classes in diffrent files so it is easy for me to see where each class etc. would be in the file structure.
-
-
iProgram over 7 yearsThanks for the answer. I knew there was internal, however since all the code is in one unit, this means that I may as well have it as public.
-
Sulthan over 7 years@iProgram But that's the problem. You have all the code in one unit.
-
iProgram over 7 yearsThourght that was how apps where ment to be. So when making applications, wverything should be in diffrent units? If so, what is the best way in doing this? Or is that for another subject? While I am not new to development, I am if you know what I mean.
-
Alex S over 7 yearsThere are several design patterns but the most common is Model-View-Controller
-
DEADBEEF over 6 yearsThe problem is the superclass and the subclass will have to be in the same file. It would be a code design issue.
-
Aaron about 6 yearsThere isn't a better answer, though since "inheritance" is an "axis" the designers decided not to employ. The only practical solution is to use file separation for instance variables and intelligently use files to separate that omitted "axis" of access control, the one presented by D4ttatraya.
-
Jerem Lachkar over 3 yearsDon't understand why this language still doesn't offer such a basic feature. Coming from Java/Android, I have to spend hours to find DIY workarounds to make on my own basic C++ like feaures such as protected or abstract classes, while so many other languages just have them already set up (PHP, C#, Java, Kotlin, ..)
-
Fattie over 3 years(FTR THIS good article medium.com/ios-os-x-development/… links to, indeed, the exact place in the Swift Guys's Writing where they justify this issue. For me, it's all whack, give me assembler :) )
-
Jerem Lachkar over 3 yearslol, I actually find Java really good at enforcing rules at compile time, coming from UML business models. And a lot of languages just have these C++ like features. The fact that Swift hasn't force me to spend time to revisit my UML business logic which is quite frustrating...
-
Fattie over 3 yearsFor the full Good Apple / Bad Apple experience, have a muck around with CoreData! Oh my ..