Chap. 20 Extensions precondition()

My precondition function does not work for the Car structure.

The book creates a firstCar instance with the fuel level: 0.5 gallons, which is within the condition fuel level newValue <= 1.0 && newValue >= 0.0. No precondition failure is expected in this case.

To test the precondition, I created a secondCar instance with the fuel level at various levels greater than 1.0, and my program did not stop execution after displaying the message, “New value must be between 0 and 1.”

I did an additional test, secondCar.fuelLevel <= 1.0, which evaluated to “false” in the results sidebar.

Does anyone else have this experience? Xcode Version 14.3.1

I also modified the precondition test by removing the “&& newValue >= 0.0” with the same results (no stopped execution and no precondition message display).

It’s still working correctly for me, if I set fuelLevel to anything outside the 0-1 range I get an error when the program runs.

Post your code so we can see if there’s a problem with it.

Looks like I spoke too soon. If I set the fuel level using the initializer, it bypasses the precondition check. This code:

var newCar = Car(make: "Honda", model: "Civic", year: 2023, fuelLevel: 2)

doesn’t generate an error, but this

newCar.fuelLevel = 2


This is because didSet and willSet are not invoked during initialization (I don’t think the book ever mentions this). Even if you define your own memberwise initializer it still won’t trigger the willSet precondition on fuelLevel, you have to add a precondition to the initializer to get it to fail:

struct Car {
    init(make: String, model: String, year: Int, fuelLevel: Double) {
        precondition(fuelLevel <= 1.0 && fuelLevel >= 0.0, "fuel level must be between 0 and 1.")
        self.make = make
        self.model = model
        self.year = year
        self.fuelLevel = fuelLevel

Thank you for your reply, and recommended implementations for willSet and precondition. I looked at the documentation for precondition but probably not willSet.