Swift : 如何使用来自 super class 的枚举变量?

Swift : How to use enum variable from super class?

我一直在尝试继承并为我的枚举变量赋值,但它每次都显示以下错误。

以下是示例源代码(实际代码我不能post这里)

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
}

这是参考。我的游乐场代码快照。

看起来该值取决于 class,即,您不需要在实例的生命周期内更改其值。如果是这种情况,您可以将其更改为计算 属性:

var animalType: AnimalsType { return .none }

override var animalType: AnimalsType { return .underwater }

另一种可能性是定义存储的属性一次,并在init中为每个class赋初始值。

这与它是枚举类型这一事实无关。 Swift 不支持覆盖存储的属性。我会说你在这里有两个选择:

使其成为计算的 属性

class Wild : Animals {
    var animalType: AnimalsType { .none }
}

class Crocodile : Wild {
    override var animalType: Animals.AnimalsType { .underwater }
}

之所以可行,是因为可以覆盖计算的属性。覆盖计算的 属性 可以说比覆盖存储的 属性 更有意义,因为毕竟存储的属性实际上没有任何可覆盖的东西。它们只是价值观。

使其成为初始化程序的一部分

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)
    }
}

取决于您想要实现的目标,任何一种方式都可能更适合您的需求。