I found this example in an online video and I can't really grasp its importance and what is happening behind the scene:
class Person {
private var _name: String!
var name: String {
return _name
}
init(name: String){
_name = name
}
}
In the video he mentions that private variables are meant to prevent classes from manipulating the data, but I can't understand why that would be a problem and how it would even happen.
Can someone please explain this to me like i'm 5?
Thanks for the help
Can someone please explain this to me like i'm 5?
OK, my five-year old friend, you are familiar with the "stranger = danger" rule, right? Sometimes, your objects need to interact with strangers. Although in many situations strangers interacting with your object are well-meaning, occasionally you would run across ones who want to harm your object, for example, by changing its name:
// If name were public, anyone could do this:
somePerson._name = "nasty-boy" // Not a good name!
In order to protect your object from strangers who want to rename them you make important things inaccessible to anyone outside your object by marking them private
. This keeps these important things inaccessible to anyone outside your object. Object's own methods, however, can freely access private variables, for example, to return them to strangers for reading, but not for writing:
var name: String {
return _name
}