Swift: 在子类中声明了一个常量,但在超类中仍然有对它的引用?

Swift: Declaring a constant in a subclass but still have a reference to it in the superclass?

假设您有 class Apple 和几个子 classes。

class Apple {
  let color = ""
}

class redDelicious :Apple {
  let color = "Red"
}

class grannySmith :Apple {
  let color = "Green"
}

func eatApple (appleToEat: Apple)
{
  if appleToEat.color == "Red" {
    //do something
  } else if appleToEat.color == "Green"
  {
    //do something else
  }
}

问题是 swift 不允许我调用 "color" 属性 但我想确保它在子 class 中定义。我还想确保每个苹果都有一种颜色,这样我就可以在 Apple 的每个子类上调用颜色 属性。在这种情况下,最好的解决方案是什么?

你可以这样做:

class Apple {
    let color: String
    init(color: String) {
        self.color = color
    }
}

class RedDelicious: Apple {
    init() {
        super.init(color: "Red")
    }
}

或者,您可以使用只读计算属性:

class Apple {
    var color: String { return "" }
}

class RedDelicious: Apple {
    override var color: String { return "Red" }
}

如果 color 只能是某些值,则可能值得使用枚举,例如:

class Apple {
    enum Color {
        case Red, Green
    }

    let color: Color
    init(color: Color) {
        self.color = color
    }
}

class RedDelicious: Apple {
    init() {
        super.init(color: .Red)
    }
}

在你的 eatApple 函数中,你会做:

func eatApple (appleToEat apple: Apple) {
    switch apple.color {
        case .Red  : // ...
        case .Green: // ... 
    }
}