Declaring and using a bit field enum in Swift

前端 未结 14 2020
余生分开走
余生分开走 2020-12-13 09:24

How should bit fields be declared and used in Swift?

Declaring an enum like this does work, but trying to OR 2 values together fails to compile:

enum         


        
14条回答
  •  臣服心动
    2020-12-13 09:38

    Task

    Get all flags from flags_combination. Each flag and flags_combination are integers. flags_combination = flag_1 | flags_2

    Details

    • Xcode 11.2.1 (11B500), Swift 5.1

    Solution

    import Foundation
    
    protocol FlagPrototype: CaseIterable, RawRepresentable where RawValue == Int {}
    extension FlagPrototype {
        init?(rawValue: Int) {
            for flag in Self.allCases where flag.rawValue == rawValue {
                self = flag
                return
            }
            return nil
        }
        static func all(from combination: Int) -> [Self] {
            return Self.allCases.filter { return combination | $0.rawValue == combination }
        }
    }
    

    Usage

    enum Flag { case one, two, three }
    extension Flag: FlagPrototype {
        var rawValue: Int {
            switch self {
            case .one: return 0x1
            case .two: return 0x2
            case .three: return 0x4
            }
        }
    }
    
    var flags = Flag.two.rawValue | Flag.three.rawValue
    let selectedFlags = Flag.all(from: flags)
    print(selectedFlags)
    if selectedFlags == [.two, .three] { print("two | three") }
    

提交回复
热议问题