ios - 无法更改父类(super class)变量 "description"

标签 ios swift inheritance subclass superclass

我正在尝试学习 Swift 中继承的概念,并提出了以下代码。我在子类中修改变量“numberOfWheels”没有问题,但是当我试图在子类中修改变量“description”时,Xcode 显示错误:

cannot assign to property "description" is a get only property

因为我对 Swift 比较陌生,所以无法解决这个问题?有人可以给我提供一个如何解决这个问题的代码示例吗?非常感谢您的帮助!

class Vehicle{
    var numberOfWheels = 0
    var description: String{
        return "\(numberOfWheels) wheels"
    }
}

class Bicycle: Vehicle {
    override init(){
        super.init()
        numberOfWheels = 2
        description = "\(numberOfWheels) wheels, more is good"
    }
}

enter image description here

最佳答案

description 是只读计算属性,因此不能直接赋值。它通常用于为实现 CustomStringConveritble 的类提供字符串转换以用于打印目的。如果您确实想在子类中重写description,则应该按如下方式操作:

override var decsription: String {
    return "\(numberOfWheels) wheels, more is good"
}

关于ios - 无法更改父类(super class)变量 "description",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001741/

相关文章:

ios - uitableview 中的多个 Segue

ios - 使用 strokeColor,从中心到圆周绘制一条线

swift - 从 Vapor 3 中的作业访问服务

ios - 在 iOS 中使用委托(delegate)进行后台请求

objective-c - iPhone 项目默认为 iPad View Controller

ios - 为什么 Apple 使用此 "if let"代码?

swift - 按下 Shift 键时强制小写

c++ - 未调用基本复制构造函数

c - C中的继承

c++通过枚举定义对象类型