George Katsanos
George Katsanos

Reputation: 14175

Initializers versus Default Property values

As I am going through the Swift documentation, I learned there are two ways to "initialize" variables in a class.

  1. By simply declaring default property values:
class Vehicle {
    var numberOfWheels = 4
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) per hour"
    }
    func makeNoise() {
        print("vroom vroom")
    }
}

class Bicycle: Vehicle {
    var hasBasket = true
}
  1. By using the init method
class Vehicle {
    var numberOfWheels: Int
    var currentSpeed: Double
    init(numberOfWheels: Int, currentSpeed: Double) {
        self.numberOfWheels = numberOfWheels
        self.currentSpeed = currentSpeed
    }
    var description: String {
        return "traveling at \(currentSpeed) per hour"
    }
    func makeNoise() {
        print("vroom vroom")
    }
}

class Bicycle: Vehicle {
    var hasBasket: Bool
    init() {
        hasBasket = true
        super.init(numberOfWheels: 2, currentSpeed: 10)
    }
}

Of course these two code samples have different results, but in general, the first method seems a bit cleaner (less code).

Why would I use the one over the other and do you see any problems or things that could simplified in either solution?

Upvotes: 0

Views: 47

Answers (1)

Ian Moses
Ian Moses

Reputation: 611

Your second method (init) allows you to pass in variables which makes the class more flexible. For example if you want to instantiate various vehicles via your Vehicle class having a different number of wheels, you may pass in:

let atv = Vehicle(numberOfWheels: 4, currentSpeed: 20)
let motorcycle = Vehicle(numberOfWheels: 2, currentSpeed: 40)

Default values, to your point, are much nicer if the value is always the same than having to pass some constant value in for all classes.

Another option is instantiating and then updating properties after doing so:

let atv = Vehicle()
atv.numberOfWheels = 4

But being able to initialize with parameters may be desired for a variety of reasons:

  1. Safety. You may want to require these class properties gain values on initialization

  2. Readability. More compact.

  3. Flexibility. You may create multiple convenience inits so you can initialize your vehicle class using different parameters. Say numberOfWheels is irrelevant but you do want to initialize with color. You can imagine a convenience init so that you may instead initialize like this:

    let rainbowVain = Vehicle(color: UIColor.White)

For your first initialization method, sometimes the code is a bit cleaner in this format, especially for viewControllers.

var description: String {
    return "traveling at \(currentSpeed) per hour"
}

This gets into computed properties which you can look more into if interested. Hope this helps some.

Upvotes: 1

Related Questions