欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

swift枚举

程序员文章站 2022-03-06 17:49:45
...

1、枚举的使用

//枚举
enum Direction {
    case sorth
    case north
    case west,east
}

var direction = Direction.east
print(direction)

switch direction {
case .sorth:
    print("sorth")
default:
    print("other")
}

//MemoryLayout  stride分配占用空间大小, size实际占用的空间大小, alignment对齐参数
print("Direction内存",MemoryLayout<Direction>.stride,MemoryLayout<Direction>.size,MemoryLayout<Direction>.alignment)
//打印结果 Direction内存 1 1 1  

2、关联值

将枚举的成员值和其他类型的值关联在一起

enum DateEnum {
    case digist(year: Int, month: Int, day: Int)
    case string(String)
    case num(Int,Int,Int)
}
var date = DateEnum.digist(year: 2020, month: 1, day: 1)
date = .string("2020-1-1")

switch date {
    //关联值可以为 let 也可以为 var
case let .digist(year: year, month: month, day: day):
    print(year,month,day)
case .string(var str):
    str += "12"
    print(str)
case .num(let year,let month,let day):
    print(year,month,day)
}

3、原始值

枚举成员可以使用相同类型的默认值设置预先对应,这个默认值叫做原始值。

//原始值
enum CharacterEnum : Character {
    case chara1 = "A"
    case chara2 = "@"
    case chara3 = "$"
}
//隐式原始值:当枚举为 Int,String时,swift会自动分配原始值
enum Week : Int {
    case mon,thu,thir,fri
}
//上下两个等价
//enum Week : Int {
//    case mon = 0
//    case thu = 1
//    case thir = 2
//    case fri = 3
//}

enum Season : String {
    case spring,winter,summer,autumn
}
//上下两个等价
//enum Season : String {
//    case spring = "spring"
//    case winter = "winter"
//    case summer = "summer"
//    case autumn = "autumn"
//}
enum Week : Int {
    case mon,thu,thir,fri
}

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

//原始值不占用枚举的内存空间
var thu = Week.thu
print("thu内存地址",Mems.ptr(ofVal: &thu)) //内存地址0x000000010000fba1  存放数据0x01
print("Week内存",MemoryLayout<Week>.stride,MemoryLayout<Week>.size,MemoryLayout<Week>.alignment)
//Week内存 1 1 1
var test1 = TestEnum.test1(1, 2, 3)
print("test1内存地址",Mems.ptr(ofVal: &test1)) //0x000000010000fba8  存放数据0x0000000000000001 0x0000000000000002 0x0000000000000003
print("TestEnum内存",MemoryLayout<TestEnum>.stride,MemoryLayout<TestEnum>.size,MemoryLayout<TestEnum>.alignment)
//TestEnum内存 32 25 8


注:原始值不占用枚举的内存空间

swift枚举

相关标签: swift