This was done in Playground, just to simplify.
class MyPrivateVar { private var priv: String? } var myInstance = MyPrivateVar() myInstance.priv = "Something"
No compiler warning. In fact auto-complete is showing priv
without a problem. My understanding is that outside the boundaries of {} of the class, I'm not supposed to be able to see a private anything, func
nor var
.
Am I missing something?
Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.
If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. class Geek: # Variable defined inside the class.
Outside the class, you can't access the private variable, but inside the class, you can access the private variables.
No you cannot, by any means access the private variables in java.
Access modifiers in Swift are implemented differently than other languages. There are three levels:
private
: accessible only within that particular file
internal
: accessible only within the module (project)
public
: accessible from anywhere
Unless marked otherwise, everything you write is internal
by default.
The Swift blog had a post about access control when the features were introduced in beta 4, and Apple's documentation has a chapter as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With