This is more of a concept question. Why bother with using init
?
class Person {
var name:String
var height:Double
...
init(name: String) {
self.name = name
self.height:Double
...
}
Why not just give everything a default value?
var name = "Daniel"
var height = 178.0
That way, I also won't have to worry about deciding between designated and 'convenience' inits because everything would just inherit from their superclass. Is there a reason for having this init
method?
Does it allow for coding patterns that a strictly default-value-initialized app cannot achieve? Or is it for reasons like resource/memory management?
Lets assume you have a factory that builds cars and a tool / class "BuildCar" with the properties:
var numberOfTires = 4
var color = UIColor.red()
var maxSpeed = 100// mph
Now you want to build a whole lot of your fancy cars and use your 'BuildCar' Tool to do so. All you can do is build red cars that have 4 tires, and have a max speed of 100 mph.
But what if you want to build a new car? A blue one, with 4 tires and max speed of 120? If you used init, you could change the variables easily.