Search code examples
swiftinitializationinitself

Why do I use Initializers in Swift?


I am trying to get my head around initializers in Swift. I kind of get what they do, but I dont get why I need them.

For example: (from apples documentation)

class NamedShape {
    var numberOfSides = 0
    var name: String
    var sideLength: Double

    init(name: String, sideLength: Double) {
       self.name = name
       self.sideLenght = sideLength
    }
}

If init should set an initial value, shouldn't self.sideLength equals an actual value, instead of just "sideLength". Or do I need to create an init to take in arguments to a function?

I'm so confused but would really appreciate if someone could help me.


Solution

  • The main purposes of initialisers is to initialise non-Optional variables. Your class has three variables - numberOfSides, name and sideLength. You give numberOfSides an initial value of zero, so it is happy. However, name and sideLength do not have values, which is "illegal" for a non-Optional. Therefore they must be given values in an initialiser. For example, if you comment out one of the lines in the init, you will get a compilation error because that variable will now not be initialised. And you do this when you cannot logically determine initial values at compile time - you could argue this is the case with numberOfSides too, as there is no shape that has no sides.

    Elsewhere in your code you might want to validate numberOfSides is at least 1. This could be achieved by having numberOfSides undefined at compile time, and passed in the init, whereby if it's not at least 1, your initialiser could return nil (which would mean using an failable initialiser - init?).

    Note that in your case, the name passed in the initialiser, is not the same as the name variable in the class. This is why you have to do:

        self.name = name
    

    To copy the name value passed in the initialiser into the variable in the class.