Search code examples
swiftpropertiesstructureobservers

Cannot invoke initializer for type Height with no arguments


I'm going through Apple's App Development With Swift iBook and it's been pretty smooth sailing until the structs chapter, specifically during the property observers section. I'm tasked with checking unit conversions.

struct Height {
    var heightInInches: Double {
        willSet(imperialConversion) {
            print ("Converting to \(imperialConversion)")
        }
        didSet {
            if (heightInInches == (heightInCentimeters * 0.393701)) {
                print ("Height is \(heightInInches)")
            }
        }
    }
    var heightInCentimeters: Double {
        willSet(metricConversion) {
            print ("Converting to \(metricConversion)")
        }
        didSet {
            if (heightInCentimeters == (heightInInches * 2.54)) {
                print ("Height is \(heightInCentimeters)")
            }
        }
    }
    init(heightInInches: Double) {
        self.heightInInches = heightInInches
        self.heightInCentimeters = heightInInches*2.54
    }

    init(heightInCentimeters: Double) {
        self.heightInCentimeters = heightInCentimeters
        self.heightInInches = heightInCentimeters/2.54
    }
}

let newHeight = Height()
newHeight.heightInInches = 12

From the book and Swift documentation, I think this should work. But I get an error message stating:

"Cannot invoke initializer for type 'Height' with no arguments."

  1. What does this mean and what am I misunderstanding?
  2. How do I go about fixing this?

Solution

  • Your one line at the bottom should be:

     let newHeight = Height(heightInInches: 12)
    

    heightInInches is the argument you are passing to the init method.