Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private var is accessible from outside the class

Tags:

swift

swift2

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?

like image 808
bauerMusic Avatar asked Sep 28 '14 17:09

bauerMusic


People also ask

Can you access a private variable outside of its class?

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.

How do you access variables outside 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.

Can we access private variable outside the class in Python?

Outside the class, you can't access the private variable, but inside the class, you can access the private variables.

Can we return private variable outside class Java?

No you cannot, by any means access the private variables in java.


1 Answers

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.

like image 154
Nate Cook Avatar answered Sep 20 '22 10:09

Nate Cook