When writing a large app in Swift, do I even need to use the "init" method at all?

181 Views Asked by At

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?

2

There are 2 best solutions below

1
chriOSx On BEST ANSWER

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.

1
EmilioPelaez On

If you were very careful, you could get away with it. It would require you to configure every Person object with all the correct values as soon as you create it, to prevent it from using the default values.

After just a few uses, though, that would mean more code written than just creating an init function that accepts the required values to initialize the object.

One of the dangers is that if somebody else (or you in the future) uses the code, they might initialize a Person, and not configure it properly, which could cause unexpected behaviour.

Suggestion

In many cases, you don't need to use a class, you can get away with using a struct. One of the magical properties of structs is that as long as you don't create an init method yourself, a default init is created which accepts a value for each property.

In you case, if Person was a struct, you could initialize it like this without writing the initializer yourself: Person(name: "David", height: 178)