Reputation: 23
I have been trying to inherit and assign a value to my enum variable but it shows me following error everytime.
Following is sample source code (actual code I cannot post here)
Cannot override with a stored property
animalType
class Animals : Livingrhings {
var canFly = false
enum AnimalsType {
case underwater
case soil
case none
}
}
class Wild : Animals {
var animalType : AnimalsType = .none
}
class Crocodile : Wild {
override var animalType: Animals.AnimalsType = .underwater // Error line
}
Here is ref. snapshot of my playground code.
Upvotes: 2
Views: 732
Reputation: 2048
This has nothing to do with the fact that it's an enum type. Swift doesn't support overriding stored properties. I'd say you have two options here:
Making it a computed property
class Wild : Animals {
var animalType: AnimalsType { .none }
}
class Crocodile : Wild {
override var animalType: Animals.AnimalsType { .underwater }
}
The reason this works is because computed properties can be overridden. Overriding a computed property arguably makes a bit more sense than overriding a stored property, because after all, stored properties don't really have anything to override. They're just values.
Make it part of an initializer
class Animals {
var canFly = false
let animalType: AnimalsType
init(animalType: AnimalsType) {
self.animalType = animalType
}
enum AnimalsType {
case underwater
case soil
case none
}
}
class Wild: Animals {
convenience init() {
self.init(animalType: .none)
}
}
class Crocodile: Wild {
convenience init() {
self.init(animalType: .underwater)
}
}
Depending on what you want to achieve either way might be better suited to your needs.
Upvotes: 3
Reputation: 42139
It looks like the value depends on the class, i.e., you don't need to change its value during the lifetime of an instance. If this is the case, you can change it to a computed property:
var animalType: AnimalsType { return .none }
And
override var animalType: AnimalsType { return .underwater }
Another possibility is to define the stored property once and assign the initial value in init
for each class.
Upvotes: 2