试图理解swift子类中的超级属性

试图理解swift子类中的超级属性,swift,class,Swift,Class,我正在学习swift,并试图理解在初始化子类时super属性的用法 示例代码: class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func

我正在学习swift,并试图理解在初始化子类时super属性的用法

示例代码:

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()

在您的示例中,
super
调用
NamedShape
init
方法,
Square
的超类。此方法负责初始化所有
NamedShape
所需的属性并执行任何其他设置

您尚未发布此类的代码,但此方法可能会为
numberOfSides
设置默认值,并存储
name
的值


提供了更多的细节。

super
在Swift中的基本意思是“超类”。什么是超类?在这种情况下,
NamedShape
Square
的超类

在超类中,有一个初始值设定项:

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.
}
您的
Square
类被称为
NamedShape
的“子类”。在子类中,您也声明了一个初始值设定项

init(sideLength: Double, name: String) {
    self.sideLength = sideLength
    super.init(name: name)
    numberOfSides = 4
}
在子类初始值设定项中,调用
super.init
。这就是它的意思

嘿,超级班!我想调用您的初始值设定项来帮助我初始化这个
Square
,我将为您提供所需的参数-
name

因此,超类初始值设定项完成了他的工作,并帮助您初始化一个
Square

这称为“初始值设定项委托”