init method simple example swift programming
Example below shows use of init method. It is used for initialization of the structure,class or enumeration property.
In swift, we must initialise the properties before using them. So either you can do it while declaring them if they are not going to change for all instances.
In case, if they are going to be changed for different instances then you must use init method. The example is for init method with parameters passed. init functions do not have names like other functions so they are distinguished by the parameters we passed.
a = b+2
a = c*2
var bi = CheckInit(b:3)
var ci = CheckInit(c:3)
Structure CheckInit has property a that has to initialised. If we expect a’s value different for different instances created for different purpose then we write to init method with different parameters.
When we create an instance and pass b value then accordingly the first init is called an a’s value is assined that is b+2 will give 5 and when we create ci instance and pass value of c = 3 then it calls the second initialiser and a’s value for that instance will be 6.