【Swift】枚举

image.png

定义枚举

enum Direction {
    case left
    case right
    case top
    case bottom
}

或者

enum Direction: String {
    case left, right, top, bottom
}

定义枚举原始值

enum Direction: String {
    case left 
    case right 
    case top 
    case bottom = "single bottom" //  覆盖原始值
}

迭代所有枚举值

试用CaseIterable协议

// 定义枚举值
enum Direction: String, CaseIterable {
    case left
    case right
    case top
    case bottom = "single bottom"
}

Direction.allCases.forEach {
    print($0.rawValue)
}

======
left
right
top
single bottom

枚举和Equatable

枚举默认可比较,不需要遵循Equatable

print(Direction.left == Direction.right)
===
false

带参数的枚举和Equatable

如果关联参数遵循Equatable,枚举会自动适配,但是得显式声明

enum Animal: Equatable {
    case dog(Int)
    case cat(Int)
    case monkey(Int)
}

print(Animal.dog(0) == Animal.cat(1))
===
false

如果参数是对象,需要枚举对象和关联对象需要显式遵循Equatable

enum Book: Equatable {
    case English(String)
    case Chinese(BookInfo)
}

struct BookInfo: Equatable {
    let pages: Int
    let name: String
}

let english = Book.English("en")
let chinese = Book.Chinese(BookInfo(pages: 9, name: "zh"))
print(english == chinese)
===
false
false

带泛型参数的枚举值

Equatable并不容易遵循,可以使用guard let 或者 if let定义判断, 轻松访问关联值

enum Result<Success, Failure> where Failure: Error {
    case success(Success)
    case failure(Error)
}

extension Result {
    public var error: Error? {
        guard case .failure(let error) = self else {
            return nil
        }
        return error
    }
    
    public var value: Success? {
        if case .success(let value) = self {
            return value
        }
        return nil
    }
}

fallthrough在枚举中的应用

fallthrough 关键字允许你明确要求从一个 case 贯穿到下一个 case,无论下一个 case 的条件是否匹配。

var person = "person is"
let sex = Sex.man
switch sex {
case .man:
    person += "man"
    fallthrough
default:
    person += " ok"
}

print(person)
===
person is aman ok

枚举在SwiftUI中的应用

ForEach(Direction.allCases, id: \.self) {
    print($0)
}

在枚举中实现Identifiable协议的 var id: String 属性,初始化就可以去掉id

enum Direction: String, CaseIterable, Identifiable {
    case left
    caseright
    case top
    case bottom = "single bottom"
    
    var id: String { rawValue }
}

ForEach(Direction.allCases) {
    print($0)
}

扩展OptionSet

创建OptionSet

struct BTCacheType: OptionSet {
    
    let rawValue: UInt
    
    static let disk = BTCacheType(rawValue: 1 << 0)
    static let memory = BTCacheType(rawValue: 1 << 1)
    static let none = BTCacheType(rawValue: 1 << 2)
    static let all = BTCacheType(rawValue: 1 << 3)
    
    static let standard: BTCacheType = [.disk, .memory]
}

===
 1 << 0 等于不动,所以结果为 1
 1 << 1 等于移动 1,2的1次方, 2
 1 << 2 等于移动 2,2的2次方,4
 1 << 3 等于移动 3,2的3次方,8 
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容