【问题标题】:cannot change superclass variable "description"无法更改超类变量“描述”
【发布时间】:2016-06-30 07:54:47
【问题描述】:

我正在尝试学习 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"
    }
}

【问题讨论】:

    标签: ios swift inheritance subclass superclass


    【解决方案1】:

    description 是只读计算属性,因此不能直接分配给。它通常用于为实现CustomStringConveritble 的类提供字符串转换以用于打印目的。如果你真的想在你的子类中覆盖description,你应该这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多