03.Swift学习
2021-11-19 本文已影响0人
aven_kang
枚举
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
var dir = Direction.east;
func test() {
switch dir {
case .north:
print("north")
case .west:
print("west")
case .south:
print("south")
case .east:
print("east")
}
}
enum Direction {
case north
case south
case east
case west
}
enum Directions {
case north,south,east,west
}
}
关联值
1.有时候会将枚举的成员值跟其他类型的关联存储在一起
enum Score {
case points(Int)
case grade(Character)
}
var score = Score.points(96)
score = .grade("A")
截屏2021-10-21 下午1.57.26.png
原始值
截屏2021-10-21 下午2.04.25.png隐式原始值
截屏2021-10-21 下午2.06.53.png递归枚举
截屏2021-10-21 下午2.11.49.png使用递归枚举的时候,需要加入关键字indirect
MemoryLayout
用于查询内存占用
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let pwd = Passwor.number(5, 6, 7, 8)
print(MemoryLayout.size(ofValue: pwd)); // 33
print(MemoryLayout.stride(ofValue: pwd));// 40
print(MemoryLayout.alignment(ofValue: pwd));// 8
}
enum Passwor {
case number(Int, Int, Int, Int)
case other
}
}
.size 是指实际占用大小
.stride 是指系统分配时给了多大
.alignment 是指按多大来对齐