Setter variable can be explicitly verified

Jul 27, 2014 00:00 · 147 words · 1 minute read swift

When you use a setter in your class, Swift will autovivify a default variable - newValue.

However, following the logic of even a simple example can be confusing when employing this

class PassengersToVehicleRatio {
    var numberOfVehicles: Int = 5
    
    // assume 4 passengers per vehicle
    var passengerTotal: Int {
    get {
        return 4 * numberOfVehicles
    }
    set {
        numberOfVehicles = newValue / 4
    }
    }
}

var passengers = PassengersToVehicleRatio()
passengers.passengerTotal // 20 passengers
passengers.passengerTotal = 30 // 7 vehicles required

I think it’s far nicer to take advantage of the ability to name this variable yourself

class PassengersToVehicleRatio {
    var numberOfVehicles: Int = 5
    
    // assume 4 passengers per vehicle
    var passengerTotal: Int {
    get {
        return 4 * numberOfVehicles
    }
    set(numberOfPassengersNeedingTransport) {
        numberOfVehicles = numberOfPassengersNeedingTransport / 4
    }
    }
}

var passengers = PassengersToVehicleRatio()
passengers.passengerTotal // 20 passengers
passengers.passengerTotal = 30 // 7 vehicles required