-2

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.

Yury
  • 6,044
  • 3
  • 19
  • 41
Anton Ödman
  • 451
  • 3
  • 7
  • 17
  • name and sideLength you will be set when calling the initializer, self.sideLength is the class property while sideLength is the initializer parameter there – Leo Dabus Sep 05 '16 at 22:33
  • 1
    init it is not "required" if you initialize it when declaring as you did with numberOfSides – Leo Dabus Sep 05 '16 at 22:35
  • BTW you should always make your class properties constants and add the required initializers. If you need to change any property just create a new object. – Leo Dabus Sep 05 '16 at 22:37

1 Answers1

1

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.

Michael
  • 8,891
  • 3
  • 29
  • 42