基本用法
enum Direction{
case north
case south
case east
case west
}
或者
enum Direction{
case north, south, east, west
}
var dir = Direction.west
dir = Direction. east
dir = .north
print(dir)//north
可以用在switch语法中
switch dir{
case .north:
print("north")
case .south:
print("south")
case .east:
print("east")
case .west:
print("west")
}
关联值
- 有时会将枚举的成员值跟其他类型的关联存储在一起,会非常有用
- 必要时
let
也可以改为var
enum Score {
case points(Int)
case grade(Character)
}
var score = Score.points(96)
score = .grade("A")
print("score = \(score)");//打印结果:score = grade("A")
switch score {
case let .points(i)://常量写let,也可以变量var
print(i,"points")
case let .grade(i):
print("grade",i)
}
enum Date{
case digit(year:Int,month:Int,day:Int)
case string(String)
}
var date = Date.digit(year: 2021, month: 12, day: 20)
date = .string("2021-12-21")
switch date{
case .digit(let year, let month,let day):
//case let .digit(year, month,day)://let可以放在前边也可以放在后边
print(year,month,day)
case let .string(value):
print(value)
}
原始值
- 枚举成员可以使用
相同类型
的默认值预先关联,这个默认值叫做:原始值
enum PokerSuit:Character{
case spade = "♠️"
case heart = "♥️"
case diamond = "♦️"
case club = "♣️"
}
var suit = PokerSuit.spade
print(suit)//spade
print(suit.rawValue)//♠️,取原始值
print(PokerSuit.club.rawValue)//♣️
enum Grade:String{
case perfect = "A"
case great = "B"
case good = "C"
case bad = "D"
}
print(Grade.perfect.rawValue)//A
print(Grade.great.rawValue)//B
print(Grade.good.rawValue)//C
print(Grade.bad.rawValue)//D
print(Grade.perfect)//perfect
print(Grade.great)//great
print(Grade.good)//good
print(Grade.bad)//bad
隐式原始值
- 如果枚举的原始值类型是
Int、String
,Swift会自动分配原始值
enum Direction:String{
case north = "north"
case south = "south"
case east = "east"
case west = "west"
}
等价于
enum Direction :String{
case north, south, east, west
}
print(Direction.north)//north
print(Direction.north.rawValue)//north
enum Season:Int{
case spring,summer,autumn,winter
}
print(Season.spring.rawValue)//0
print(Season.summer.rawValue)//1
print(Season.autumn.rawValue)//2
print(Season.winter.rawValue)//3
如果给定原始值,则下一个递增
enum Season:Int{
case spring=1,summer,autumn=4,winter
}
print(Season.spring.rawValue)//1
print(Season.summer.rawValue)//2
print(Season.autumn.rawValue)//4
print(Season.winter.rawValue)//5
递归枚举
indirect enum ArithExpr{
case number(Int)
case sum(ArithExpr,ArithExpr)
case difference(ArithExpr,ArithExpr)
}
或者写成
enum ArithExpr{
case number(Int)
indirect case sum(ArithExpr,ArithExpr)
indirect case difference(ArithExpr,ArithExpr)
}
indirect enum ArithExpr{
case number(Int)
case sum(ArithExpr,ArithExpr)
case difference(ArithExpr,ArithExpr)
}
let five = ArithExpr.number(5)
let four = ArithExpr.number(4)
let two = ArithExpr.number(2)
let sum = ArithExpr.sum(five, four)
let difference = ArithExpr.difference(sum, two)
func calculate(_ expr:ArithExpr) -> Int{
switch expr {
case let .number(value):
return value
case let .sum(left, right):
return calculate(left) + calculate(right)
case let .difference(left, right):
return calculate(left) - calculate(right)
}
}
print(calculate(difference))//7
MemoryLayout
- 可以使用MemoryLayout获取数据类型占用的内存大小
MemoryLayout.size//8,跟平台有关,平台是64位,所以占8字节
MemoryLayout.stride//8
MemoryLayout.alignment//8,内存对齐参数(和数据结构最大的那个,保持一致)
var age = 10
MemoryLayout.size(ofValue: age)//8
MemoryLayout.stride(ofValue: age)//8
MemoryLayout.alignment(ofValue: age)//8
enum Password{
case number(Int,Int,Int,Int)
case other
}
var pwd = Password.number(5,6,4,7)//内存为32个字节
pwd = .other//内存为32个字节
MemoryLayout.size//33个字节,实际用到的空间大小(numbers是32,other是1)
MemoryLayout.stride//40个字节,分配占用的空间大小
MemoryLayout.alignment//8个字节,对齐参数(和数据结构最大的那个,保持一致)
enum Season{
case spring,summer,autumn,winter
}
MemoryLayout.size//1
MemoryLayout.stride//1
MemoryLayout.alignment//1
enum Season:Int{
case spring=1,summer,autumn,winter
}
MemoryLayout.size//1
MemoryLayout.stride//1
MemoryLayout.alignment//1
- 关联值和原始值的区别
关联值:允许自己传值的,存储在枚举变量内存里面
原始值:不会放在枚举内存变量,枚举类型只占用一个字节,相当于存储一个tag值,去区分是哪个枚举值就可以了
enum Password{
case number(Int,Int,Bool,Int)
case other
}
print(MemoryLayout.size)//32,(32的原因是内存对齐为8,第三位需要跳过8个字节,而bool只需要占用1个字节,剩余的7个字节可以给枚举区分用,所以不需要额外多加一个字节)
print(MemoryLayout.stride)//32
print(MemoryLayout.alignment)//8
enum Password{
case number(Int,Int,Int,Bool)
case other
}
print(MemoryLayout.size)//25
print(MemoryLayout.stride)//32
print(MemoryLayout.alignment)//8
可选项
- 可选项,一般也叫可选类型,它允许将值设置为
nil
- 在类型名称后面加个
问号 ?
来定义一个可选项
var age:Int
print(age)
报错,因为age没有初始值
var age:Int?
print(age)
不报错,因为有初始值,等价于var age:Int = nil
var age:Int 和 var age:Int = 0是不等价的
var name : String? = "jack"
name = nil
var age:Int? //默认就是nil
age = 10
age = nil
var array = [1,15,40,29]
func get(_ index:Int) -> Int?{
if index<0 || index >= array.count {
return nil
}
return array[index]
}
print(get(1))//Optional(15)
print(get(-1))//nil
print(get(4))//nil
强制解包
- 可选项是对其他类型的一层包装,可以将它理解为一个盒子
- 如果为nil
,那么它是个空盒子
- 如果不为nil
,那么盒子里装的是:被包装类型的数据 - 如果要从可选项中取出被包装的数据(将盒子里装的东西取出来),需要使用
感叹号!
进行强制解包
var age:Int? = 10
var num = age + 20
//报错:Value of optional type 'Int?' must be unwrapped to a value of type 'Int',因为age是一个可选类型,可以理解为一个盒子,不能拿盒子直接来操作,要把盒子里的内容拿出来,要用到`!`进行强制解包取出内容
var num = age! + 20
- 如果对值为
nil
的可选项(空盒子)进行强制解包,将会产生运行时错误,所以在强制解包时要确定确实有值才可以强制解包
var age:Int?
age!
//报错:Fatal error: Unexpectedly found nil while unwrapping an Optional value
判断可选项是否包含值
let number = Int("123")
if number != nil{
print("字符串转换整数成功:\(number!)")
}else{
print("字符串转换整数失败")
}
可选项绑定
- 可以使用
可选项绑定
来判断可选项是否包含值
- 如果包含就自动解包,把值赋给一个临时的常量(let
)或者变量(var
),并返回true
,否则返回false
if let number = Int("123") {
print("字符串转换整数成功:\(number)")
//number是强制解包之后的Int值
//number作用域仅限于这个大括号
}else{
print("字符串转换整数失败")
}//字符串转换整数成功:123
enum Season:Int {
case spring = 1,summer,autumn,winter
}
if let season = Season(rawValue: 6) {
switch season {
case .spring:
print("the season is spring")
default:
print("the season is other")
}
}else{
print("no such season")
}
- 可选项绑定的与条件用
,
不能用&&
等价写法
if let first = Int("4") {
if let second = Int("42") {
if first
while
循环中使用可选项绑定
var strs = ["10","20","abc","-20","-30"]
var index = 0
var sum = 0
while let num = Int(strs[index]),num>0 {
sum += num
index += 1
}
print(sum)
空合并运算符 ??
-
a ?? b
-a
是可选项
-b
是可选项或者不是可选项
-b
跟a
的存储类型必须相同(如果a为int?,那么b也必须为int?或者int)
- 如果a
不为nil
,则返回a
- 如果a
为nil
,就返回b
- 如果b
不是可选项,返回a
时会自动解包
let a:Int? = 1
let b:Int? = 2
let c = a ?? b
print(c)
//c是Int?,Optional(1)
let a:Int? = nil
let b:Int? = 2
let c = a ?? b
print(c)
//c是Int?,Optional(2)
let a:Int? = nil
let b:Int? = nil
let c = a ?? b
print(c)
//c是Int?,nil
let a:Int? = 1
let b:Int = 2
let c = a ?? b
print(c)
//c是Int,1
总结下来就是说:空合并运算符返回的类型取决于b的类型
多个??
一起使用
let a:Int? = 1
let b:Int? = 2
let c = a ?? b ?? 3
print(c)
//c是Int,1
let a:Int? = nil
let b:Int? = 2
let c = a ?? b ?? 3
print(c)
//c是Int,2
let a:Int? = nil
let b:Int? = nil
let c = a ?? b ?? 3
print(c)
//c是Int,3
//返回类型看最后边的类型
??
跟if let
配合使用
let a:Int? = nil
let b:Int? = 2
let c = a ?? b ?? 3
if let c = a ?? b{
print(c)
}//2
//类似于if a != nil || b != nil
if
语句实现登录
func login(_ info:[String:String]){
let username:String
if let tmp = info["username"] {
username = tmp
}else{
print("请输入用户名")
return
}
let password:String
if let tmp = info["password"] {
password = tmp
}else{
print("请输入密码")
return
}
print("用户名:\(username)", "密码:\(password)","登录ing")
}
login(["username":"jack","password":"123456"])//用户名:jack 密码:123456 登录ing
login(["password":"123456"])//请输入用户名
login(["username":"jack"])//请输入密码
guard
语句
guard 条件 else{
//do something....
退出当前作用域(必须写下面的退出当前作用域代码,不然会报错)
//return、break、continue、throw error
}
- 当
guard
语句的条件为false
时,就会执行大括号里面的代码 - 当
guard
语句的条件为true
时,就会跳过guard
语句 -
guard
语句特别适合用来“提前退出” - 当使用
guard
语句进行可选项绑定时,绑定的常量(let
)、变量(var
)也能在外层作用域中使用
func login(_ info:[String:String]){
guard let username = info["username"] else {
print("请输入用户名")
return
}
guard let password = info["password"] else {
print("请输入密码")
return
}
print("用户名:\(username)", "密码:\(password)","登录ing")
}
login(["username":"jack","password":"123456"])//用户名:jack 密码:123456 登录ing
login(["password":"123456"])//请输入用户名
login(["username":"jack"])//请输入密码
隐式解包
- 在某些情况下,可选项一旦被设定值之后,就会一直拥有值
- 在这种情况下,可以去掉检查,也不必每次访问的时候都进行解包,因为他能确定每次访问的时候都有值
- 可以在类型后面加个感叹号
!
定义一个隐式解包的可选项 总结:可以确定可选项一直有值的情况下可以用隐式解包
//隐式解包的可选项
let num1:Int! = 10
let num2:Int = num1
print(num2)
let num1:Int! = 10
let num2:Int = num1
if num1 != nil {
print(num1+6)//16
}
if let num3 = num1 {
print(num3)
}
let num1:Int! = nil
//Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
let num2:Int = num1
字符串插值
- 可选项在字符串插值或者直接打印时,编译器会发出警告
var age:Int? = 10
print("my age is \(age)")//my age is Optional(10)
//String interpolation produces a debug description for an optional value; did you mean to make this explicit?
print(age)//Optional(10)
//Expression implicitly coerced from 'Int?' to 'Any'
- 至少有三种方法消除警告
print("my age is \(age!)")//my age is 10
print("my age is \(String(describing: age))")//my age is Optional(10)
print("my age is \(age ?? 0)")//my age is 10
多重可选项
var num1:Int? = 10//包装了一个Int类型的可选类型
var num2:Int?? = num1//包装了一个可选类型的可选类型
var num3:Int?? = 10
print(num2 == num3)//true
var num1:Int? = nil
var num2:Int?? = num1
var num3:Int?? = nil
print(num2 == num3)//false
print(num1 == num3)//false,返回值类型不同
print((num2 ?? 1) ?? 2)//2
print((num3 ?? 1) ?? 2)//1
- 可以使用
lldb
命令frame variable -R
或者fr v -R
查看区别
枚举变量的内存布局
- 有多个case的情况下,1个字节存储成员值
- N个字节存储关联值(N取占用内存最大的关联值),任何一个case的关联值都共用这N个字节
enum TestEnum {
case test1(Int,Int,Int)
case test2(Int,Int)
case test3(Int)
case test4(Bool)
case test5
}
var e = TestEnum.test1(1, 2, 3)
//01 00 00 00 00 00 00 00
//02 00 00 00 00 00 00 00
//03 00 00 00 00 00 00 00
//00
//00 00 00 00 00 00 00
e = .test2(4, 5)
//04 00 00 00 00 00 00 00
//05 00 00 00 00 00 00 00
//00 00 00 00 00 00 00 00
//01
//00 00 00 00 00 00 00
e = .test3(6)
//06 00 00 00 00 00 00 00
//00 00 00 00 00 00 00 00
//00 00 00 00 00 00 00 00
//02
//00 00 00 00 00 00 00
e = .test4(true)
//01 00 00 00 00 00 00 00
//00 00 00 00 00 00 00 00
//00 00 00 00 00 00 00 00
//03
//00 00 00 00 00 00 00
e = .test5
//00 00 00 00 00 00 00 00
//00 00 00 00 00 00 00 00
//00 00 00 00 00 00 00 00
//04
//00 00 00 00 00 00 00
大小端:高高低低存储
enum TestEnum {
case test
}
var t = TestEnum.test
print(MemoryLayout.size)//0
print(MemoryLayout.stride)//1
print(MemoryLayout.alignment)//1
只有一个case,不需要字节存储成员值
enum TestEnum {
case test(Int)
}
var t = TestEnum.test(10)
print(MemoryLayout.size)//8
print(MemoryLayout.stride)//8
print(MemoryLayout.alignment)//8
enum TestEnum {
case test1,test2
}
var t = TestEnum.test1
print(MemoryLayout.size)//1
print(MemoryLayout.stride)//1
print(MemoryLayout.alignment)//1