Swift学习笔记-枚举

xiaoxiao2022-06-11  35

定义枚举类型

定义的语法和C/C++很像,只不过前面多了case语句

enum TextColor{ case blue case black case green case red case white }

创建枚举实例

第一次创建枚举实例的时候必须指定枚举枚举类型和值,之后的代码可以省略类型

//显示类型声明 var color1:TextColor=TextColor.black //使用推断类型 var color2=TextColor.blue //给枚举实例赋值 color2 = .white //判断枚举实例的值 if (color2 == .white){ print("color is white") }

使用switch语句处理枚举值

不要忘记switch语句必须能处理值的所有可能性

switch color1 { case .blue: print("color is blue") case .black: print("color is black") case .green: print("color is green") case .red: print("color is red") case .white: print("color is white") }

原始值枚举

不同于C/C++,枚举实例并非是整形,不过利用原始值这一特性,也可以得到同样的效果

enum TextColor:Int{ case blue=1 case black=2 case green=3 case red=40 case white=60 }

对于整形,如果不给枚举成员赋值,则默认从0开始,并依次递增 对于字符串,如果不给枚举成员赋值,则会使用成员本身的名称

enum TextColor:Int{ case blue=2 case black//3 case green//4 case red//5 case white//6 }

通过rawValue可获取原始值

print(TextColor.red.rawValue)

将原始值转换为枚举值,由于可能转换失败,所以返回的是可空类型

if let myColor=TextColor(rawValue: 200){ print("convert success \(myColor)") }else{ print("convert failed") }

枚举中的方法

不同于其他编程语言,swift的枚举中可以定义方法,其中self代表自身实例

enum TextColor{ case blue case black case green func getColorValue()->Int{ switch self { case .black: return 1 case .blue: return 2 case .green: return 3 } } } var color=TextColor.black; print(color.getColorValue())//1

在swift中,枚举是值类型,值类型的方法不能对self进行修改,如果需要修改,需要标记这个方法为mutating

enum TextColor{ case blue case black case green mutating func setColorValue(){ self = .blue } } var color=TextColor.black; color.setColorValue() print(color)//blue

关联值

枚举中的不同成员可以有不同的关联值,使用关联值可以将数据附加在枚举实例上

enum Shape{ //点 case point //正方形 case oquare(side:Double) //长方形 case rectangle(width:Double,height:Double) //获取面积 func area() -> Double{ switch self { case .point: return 0 case let .oquare(side: s): return s * s case let .rectangle(width: w, height: h): return w * h } } } var shape1=Shape.oquare(side: 10.0) var shape2=Shape.rectangle(width: 20.0, height: 40.0) print(shape1.area()) print(shape2.area())

递归枚举

当关联值的类型为当前枚举类型时,会出现递归的情况,这个时候编译器会报错,因为编译器无法确定该类型所占用的内存,这个时候可以使用关键字indirect,告诉编译器把数据放到指针指向的地方,这个时候枚举实例占用的内存就变成了一个指针的长度

indirect enum Shape{ case oquare(parentShape:Shape) }
转载请注明原文地址: https://www.6miu.com/read-4930616.html

最新回复(0)