edmamerto
edmamerto

Reputation: 8165

Trying to understand super attribute in swift subclasses

I'm learning swift and I'm tryong to understand the use of the super attribute when initializing subclasses

sample code:

class Square: NamedShape {
    var sideLength: Double

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

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

    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."
    }
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()

Upvotes: 0

Views: 55

Answers (2)

Sweeper
Sweeper

Reputation: 273540

super in Swift basically means "the superclass". And what is a superclass? In this case, NamedShape is the superclass of Square.

And in the superclass, there is an initializer:

init(name: String) {
    //code not given so I cannot tell you want is in here
    //You just need to know that there is an initializer.
}

And your Square class is called the "subclass" of NamedShape. In the subclass, you declared an initializer too.

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

In the subclass initializer, you call super.init. This is what it means,

Hey superclass! I want to call your initializer to help me initialize this Square, I'll give you the arguments needed - name.

And so the superclass initializer does his job and helps you initialize a Square.

this is called "initializer delegation".

Upvotes: 1

Aaron Brager
Aaron Brager

Reputation: 66302

In your example, super calls the init method of NamedShape, the superclass of Square. This method is responsible for initializing all of NamedShape's required properties and doing any other setup.

You haven't posted the code for this class, but it looks like this method might set a default value for numberOfSides and stores the value of name.

The Swift Initialization docs provide many more details.

Upvotes: 1

Related Questions