尝试从基类继承时出错:无法覆盖存储的属性

Error when trying to inherit from base class: cannot override stored property

我做错了什么?

class NamedShape {
    var numberOfSides: Int = 0
    var name: String

    init(name: String) {
        self.name = name
    }

    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}


class Circle: NamedShape{
    var radius: Double

    // Here it says:"Cannot override with a stored property ‘name':
    var name: String

    init(radius: Double, name: String) {
        self.radius = radius
        super.init(name: name)
    }

    func area(radius: Double) ->Double{
        var area: Double = radius * radius * 3.14
        return area
    }

    override func simpleDescription() -> String {

        // Here it says that 'name' is ambiguous:
        return "A circle by the name of \(name)with the area of \(area(radius))"
    }
}

let test = Circle(radius:5.1,name: myCircle)

我不是 Swift 方面的专家,但看起来你正在定义另一个 属性 的子 class(圆),它恰好被称为与a 属性 在它的 superclass (NamedShape).

您的 NamedShape 的整个想法似乎应该是 class 存储名称。那为什么不跳过子class中的属性name呢?我的意思是,删除第一个错误所在的行

别担心。您仍然可以在 subclass 中引用 name。这就是定义 Circle 以扩展 NamedShape.

的全部意义所在