Swift

Swift——4、枚举

2019-08-04  本文已影响0人  天空像天空一样蓝

枚举

枚举

关联值

关联值

caset let .points(i) let也可以定义为var
caset let .points(i) let 定义在 前面,表示 i 的类型为let
case .digit(let year, let month, let day) let 定义在里面,分别表示不同的类型,定义在外面的话,里面只能是一种类型

关联值举例

原始值

原始值
隐式原始值
隐式原始值

递归枚举

递归枚举

MemoryLayout

enum Password {
    case number(Int, Int, Int, Int) // 32
    case other // 1
}


print("stride == \(MemoryLayout<Password>.stride)") // stride == 40
print("size == \(MemoryLayout<Password>.size)") // size == 33
print("alignment == \(MemoryLayout<Password>.alignment)") // alignment == 8

enum TestEnum {
    case test1(Int, Int, Int)
    case test2(Int, Int)
    case test3(Int)
    case test4(Bool)
    case test5
}

/// 01 00 00 00 00 00 00 00
/// 03 00 00 00 00 00 00 00
/// 04 00 00 00 00 00 00 00
/// 00 00 00 00 00 00 00 00
var e = TestEnum.test1(1, 3, 4)
print(Mems.ptr(ofVal: &e))
/// 05 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 = .test3(5)
/// 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 = .test4(true)

观察上面代码,可以得出:

enum Password {
    case other(Int)
}
stride == 8
size == 8
alignment == 8

注意点:观察下面代码

enum Password {
    case other
}

print("stride == \(MemoryLayout<Password>.stride)") // stride == 1
print("size == \(MemoryLayout<Password>.size)") // size == 0
print("alignment == \(MemoryLayout<Password>.alignment)") // alignment == 1

上一篇下一篇

猜你喜欢

热点阅读