Search code examples
iosmacosswiftswift-playground

Swift: Order of super.init and self.attribute in init


I'm trying to init a subclass like the following:

class NameShape{
    var numberOfSide: Int = 0
    var name:String
    func simpleDescription() -> String {
        return "A square with \(numberOfSide) sides."
    }
    init (name: String){
        self.name = name
        }
}

class Square:NameShape{
    var sideLength: Double
    init(name: String, sideLength: Double){
        super.init(name: name)
        self.sideLength = sideLength
        numberOfSide = 4
    }

    func area() ->Double {
        return sideLength * sideLength
    }

    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."
    }

}

I get an error property 'self.sideLength' not initialized at super.init call, so I switch self.sideLength = sideLength and super.init(name: name), such as:

class Square:NameShape{
    var sideLength: Double
    init(name: String, sideLength: Double){            
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSide = 4
    }

    func area() ->Double {
        return sideLength * sideLength
    }

    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."
    }

}

and It's fine now, can someone explain the principles behind? Thx!!!


Solution

  • The reason why you're change fixed it is because of Apple's "safe" approach to this language. Any non-wrapped and non-initialized variables that aren't initialized before a method call will throw a compiler error. It's a safety feature in Swift. Basically, the compiler is trying to save you from doing something like this:

    init(name: String, sideLength: Double){            
        super.init(name: name)
        someFunctionThatUsesSideLengthBeforeItsInitialized(sideLength)
        self.sideLength = sideLength
        numberOfSide = 4
    }
    

    This method someFunctionThatUsesSideLengthBeforeItsInitialized might cause a exception. In my opinion, super-class functions like super.init should be exempt from this rule.