Let's say you had the class Apple with several subclasses.
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
}
}
The problem is that swift won't let me call the "color" property but I want to make sure that's defined in the subclasses. I also want to make sure every apple has a color so that I can call the color property on each sublcass of Apple. What would be the best solution in this case?
You could do:
class Apple {
let color: String
init(color: String) {
self.color = color
}
}
class RedDelicious: Apple {
init() {
super.init(color: "Red")
}
}
Or instead, you could use read-only computed properties:
class Apple {
var color: String { return "" }
}
class RedDelicious: Apple {
override var color: String { return "Red" }
}
If color
can only be certain values it may be worth using an enum, for example:
class Apple {
enum Color {
case Red, Green
}
let color: Color
init(color: Color) {
self.color = color
}
}
class RedDelicious: Apple {
init() {
super.init(color: .Red)
}
}
In your eatApple
function, you would then do:
func eatApple (appleToEat apple: Apple) {
switch apple.color {
case .Red : // ...
case .Green: // ...
}
}