第三节 枚举、可选项

2021-01-30  本文已影响0人  天明天

一.枚举

1.枚举的基本用法
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

2.关联值
enun Score {
   case point(Int)
   case grade(Character)
 }  ///这里后面可以关联一个值 

var score = Score.points(96)
score = .grade("A")


image.png
3.原始值

枚举成员可以使用 相同类型的默认值预先关联,这个默认值据说原始值

enmu Point : Int{
 case x = 0
 case y = 1
 case width = 100
 case height = 10
} 

var suit = Point.x访问原始值
print(suit.rawValue)访问原始值
print(Point.y.rawValue) 访问原始值

4.隐士原始值
5.递归枚举

6. MemoryLayout 的使用

enum Password {/// 首字母大写,成员小写开头
case  num(Int,Int,Int,Int)
case other
}

var pwd = Password.numbers(5,6,7,8)//占用多少字节
pwd = .other// 

MemorLayout<Password>.stride// 40,系统实际分配的内存大小
MemorLayout<Password>.size// 33, 实际占用内存大小,有7个字节浪费掉了
MemorLayout<Password>.aliganment// 8,系统对齐参数

MemorLayout<Password>.stride// 40,系统实际分配的内存大小
MemorLayout<Password>.size// 33, 实际占用内存大小,有7个字节浪费掉了,32个字节存储 num,1个字节存储 other
MemorLayout<Password>.aliganment// 8,系统对齐参数

enum Season {
  case one, two,three,four
}
MemorLayout< Season >.stride// 1 只占用一个字节,用一个字节就可以存储这个枚举

这里主要关联值 跟 原始值的区别,以及内存占用的大小。

enum Password {/// 关联值
case  num(Int,Int,Int,Int)
case other
}
enum Season { // 这里是原始值,这个值是固定死的,不允许外部改动

  case one = 1, two,three,four
}

二. 可选类型(optional)

  1. 概念
2.强制解包
var age :Int? = 10
let ageInter : Int = age!////强制解包
print(ageInter)
3. 判断可选项是否包含着值

Int("113") 初始化新方法

let num = Int("123")
if num != nil {

print(num)
}else{
print("fail")
}
4. 可选绑定
5. 等价写法
if let first = Int("4") {
   if let second = Int("14") {
    if first < second && second < 100 {
      print ("Good")
   }
}
}

if let first = Int("4"),
    let second = Int("14"),
    first < second && second < 100 {
     print("Good")
 }
6. 空合并运算符 ??

总结, 空合并运算符?? 返回的类型其实跟 b的类型一致,b是可选类型 则返回值是 可选类型,b不是可选类型,则最后返回结果不是可选类型

7. 多个空合并运算符 ?? 一起使用
截屏2019-11-18下午3.21.27.png
8. 空合并运算符 ??if let 一起使用
let a : Int? = nil
let b :Int ? = 2

if let c = a ?? b {
   print(c)
}
// 类似于: if a != nil || b != nil 

if let c = a, let d = b {
   print(c)
   print(d)
}
// 类似于 if a !=ni && b != nil
9. if 实现登录功能

老的写法 比较麻烦


截屏2019-11-18下午4.01.34.png
guard 条件 else  {
//退出当前作用域
// return, break,continue,throw error 等必须要写
}
10. 隐式解包

尽量不要使用这种带 ! 的可选类型

11. 字符串插值
截屏2019-11-18下午4.26.36.png
12. 多重可选项目
截屏2019-11-18下午4.32.19.png
上一篇下一篇

猜你喜欢

热点阅读