self.name = name this would be the MyClass's var name: String property?
What about the name on the right side = name is that also MyClass' var name: String property?
self.name is the class property
name is the parameter passed to init()
To see the difference, you could write
init(withName: String) {
self.name = withName
}
and call as
let obj1 = MyClass(withName: "A")
So that's like var name = var name (itself = itself)?
Not at all, see above.
class MyClass {
var name: String = "Has the string value"
Is self.name = name 's value defaulted to the void/null value like an optional?
What do you mean ? not defaulted to nil here.
name is initialized with a default value, but that can be changed when creating or modyfing the instance.
Once again, if that is to hard to understand, whange int(withName: String) to better understand.
What happens if you don't put the initialization
Compiler will detect an error, unless you give an initial value when declaring the var or declare the var as optional (it gets nil value)
Any real world anology on the concept of initialization and self?
This is always tricky and often misleading to try to illustrate by real world examples and does not replace the need for a real understanding of what happens in computer world.
However, I would say:
Class is somehow the mold. It is not an object.
With the mold, you define instructions for operator, like :
- object will be of some material : clay, plaster, … ; no default value, so material woul be defined as optional value
- object will have a color (that's a property) ; by default the color will be brown
When you instantiate, you create an object instance from this mold. Now you have a physical object in hand.
But to create, you need to use some material and taint it: that's the role of init
int(material: "clay", color: blue)
this tells the operator what he has to do: use that material and taint it blue. Then of course mold it to create the object instance.
self in the instruction manual is "the object you are creating"
So the sequence is:
let obj1 = MyClass(material: "Clay", color: "Blue")
-> Operator knows he has to use clay and blue tint
The instruction manual will say
init(material: SomeMaterial, color: SomeColor)
-> To create an object from the mold, use the material and color defined in the order
-> self is referring to this real object you are creating
Hope that helps.