本文介绍了Swift枚举继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能否继承Swift的枚举?以下是测试代码:



<$



p $ p> 枚举TemperatureUnit:Int {
case Kelvin,Celcius,Farenheit
}

枚举TemperatureSubunit:Temperature {
}

生成

  error:type'TemperatureSubunit'不符合协议'RawRepresentable'


解决方案

在swift语言中,我们有Structs,Enum和Classes.Struct和Enum都被复制传递,但Classes是通过引用传递的。只有Classes支持继承,Enum和Struct不能回答你的问题,使用枚举(和结构类型)继承。看看这里




Can you inherit enum in Swift? What are the rules that one should be aware of with regards to enum inheritance?

The following test code:

enum TemperatureUnit: Int {
    case Kelvin, Celcius, Farenheit
}

enum TemperatureSubunit : Temperature {
}

generates

error: type 'TemperatureSubunit' does not conform to protocol 'RawRepresentable'
解决方案

In swift language we have Structs,Enum and Classes.Struct and Enum are passed by copy but Classes are passed by reference.Only Classes support inheritance, Enum and Struct don't.So to answer your question you can't have inheritance with Enum (and Struct types). Have a look here

stackOverflow difference classes vs structs

这篇关于Swift枚举继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:37