枚举基本使用
//枚举的简单定义和简单应用
//第一种定义方式
enum Direction{
case north
case south
case east
case west
}
//第二种定义方式
enum Direction1 {
case north,south,east,west
}
//枚举的简单使用
var dir = Direction.west
dir = Direction.north
dir = .east
print(dir)
switch dir {
case .east:
print(Direction.east)
default:
break
}
//枚举关联值的使用
enum Score {
case points(Int)
case grade(Character)
case Level(String)
case LevelStr(String,String)
}
var score = Score.points(100)
score = .grade("A")
score = .Level("dddd")
score = .LevelStr("zhangsan", "lisi")
switch score {
case let .points(i):
print(i)
case let .grade(i):
print(i)
case let .Level(i):
print(i)
case .LevelStr(let str0,var str1):
print("\(str0) \(str1)")
str1 = ""
}
//枚举原始值的使用 只有在定义枚举的时候指定了类型 才可以点出原始值
enum PokerSuit:Character {
case spade = "♠"
case heart = "❤"
case diamond = "♦"
case club = "♣"
}
let suit:PokerSuit = .spade
print(suit.rawValue)
枚举值和关联值的区别
var age = 100
MemoryLayout<Int>.size //变量实际用到的内存大小
MemoryLayout<Int>.stride //变量被分配的内存大小
MemoryLayout<Int>.alignment //内存对齐参数
MemoryLayout.size(ofValue: age)
MemoryLayout.stride(ofValue: age)
MemoryLayout.alignment(ofValue: age)
enum Password {
case number(Int,Int,Int,Int)
case other
}
//枚举的内存分布控件
// 枚举变量内存 先保存关联变量 还有一个字节保存原始值 再按照对齐参数进行分配内存 枚举变量会按照最大变量的内存去分配
var pwd = Password.number(5,6,7,8)
MemoryLayout.size(ofValue: pwd)
MemoryLayout.alignment(ofValue: pwd)
MemoryLayout.stride(ofValue: pwd)
pwd = Password.other
MemoryLayout.stride(ofValue: pwd)
//原始值 原始值是不容许自定义 不会在枚举变量内存中分配空间 会在rawValue的时候获取
原始值和关联值的本质区别 在于关联值被保存在枚举变量内存中,而原始值不会保存到枚举类型变量内存中。
来源:CSDN
作者:空中海
链接:https://blog.csdn.net/liuyinghui523/article/details/104539372