关联值
enum SDate {
case digit(year:Int,month:Int,day:Int)
case string(String)
}
var date = SDate.digit(year: 2023, month: 9, day: 19)
date = .string("2023-9-19")
switch date {
case .digit(let year, let month , let day):
print(year,month,day)
case let .string(value):
print(value)
}
示例代码手势密码
enum Password {
case number(Int,Int,Int,Int)
case gesture(String)
}
var psw = Password.number(1, 2, 3, 4)
//psw = .gesture("4567")
switch psw {
case let .number(n1, n2, n3, n4):
print(n1,n2,n3,n4)
case let .gesture(str):
print(str)
}
枚举原始值
原始值 rawValue
enum AudioType : String , CaseIterable{
case playa,pausea,stopa
}
enum VideoType : String , CaseIterable{
case playv,pausev,stopv
}
: String并不是继承,而是原始值为字符串
了解隐式原始值,原始值类型是字符串,那么swift会自动分配原始值
递归枚举
indirect enum ArithExpr {
case number(Int)
case sum(ArithExpr,ArithExpr)
case difference(ArithExpr,ArithExpr)
}
var ari = ArithExpr.number(10)
var ari2 = ArithExpr.number(20)
ari = .sum(ari, ari2)
ari = .difference(ari, ari2)
func calulate(expr:ArithExpr) -> Int{
switch expr {
case let .number(value):
return value
case let .sum(a, b):
return calulate(expr: a) + calulate(expr: b)
case let .difference(a, b):
return calulate(expr: a) - calulate(expr: b)
}
}
let valur = calulate(expr: ari)
print(valur)
enum TestNum2:String {
case spring = "春天",summer,autumn,winter
}
- 底层typealias取了一个别名
- 默认添加一个可选类型的init方法
- 增加一个计算属性rawValue,用于获取枚举值的原始值
原始值不会存储在枚举的变量中,只有关联值会
enum TestNum2:String {
case spring = "春天",summer,autumn,winter
typealias RawValue = String
init?(rawValue: String) { }
var rawValue: String{
}
}
使用枚举的rawValue获取底层是调用get方法,在mach-o中找对应的地址取出字符串并返回的操作
枚举的特点:
可以包含计算属性,类型属性,不能包含存储属性
计算内存占用
let size = MemoryLayout.size(ofValue: psw) //实际占用的内存空间
let stride = MemoryLayout.stride(ofValue: psw) //分配的内存空间
let alignment = MemoryLayout.alignment(ofValue: psw)
问题:
1、原始值和关联值的区别
2、了解枚举内存空间的占用,可以计算枚举内存
网友评论