繁体   English   中英

符合 enum:int32 BinaryInteger 的问题

[英]Problems to conform enum:int32 BinaryInteger

我想要一个可以逻辑组合的 Int32 枚举。 这是我的代码,但 Xcode syas 不符合 BinaryInteger 协议:

enum AppState : Int32, CaseIterable, BinaryInteger, Numeric {
    
    typealias Words = Int32.Type;
    typealias IntegerLiteralType = Int32.Type
    typealias Magnitude = Int32.Type;
    
    static func & (lhs: AppState, rhs: AppState) -> AppState {
        return (lhs.rawValue & rhs.rawValue) as! AppState;
    }

    static func | (lhs: AppState, rhs: AppState) -> AppState {
        return (lhs.rawValue | rhs.rawValue) as! AppState;
    }

    static func + (lhs: AppState, rhs: AppState) -> AppState {
        return (lhs.rawValue + rhs.rawValue) as! AppState;
    }

    static func - (lhs: AppState, rhs: AppState) -> AppState {
        return (lhs.rawValue - rhs.rawValue) as! AppState;
    }
    
       
    case APP_UNINITIALIZED = 0;
    case APP_PREFERENCES = 1;
    case APP_INSULIN_FAVORITES = 2;
    case APP_FOODS = 4;
    case APP_CONFIGURATIONS = 8;
    case APP_FULL_INITIALIZED = 16;
}

var state : AppState;

state = AppState.APP_PREFERENCES & AppState.APP_FOODS;

你在这里有几个问题:

  1. 代码像(lhs.rawValue | rhs.rawValue) as! AppState (lhs.rawValue | rhs.rawValue) as! AppState将始终失败,因为(lhs.rawValue | rhs.rawValue)将始终是Int32类型,这与AppState 您正在寻找AppState(rawValue: lhs.rawValue | rhs.rawValue) ,它本身总是会失败,因为没有值AppState value 其原始值为(例如)3( 0b01 | 0b10 == 0b11 == 3 ) .

  2. 您正在尝试符合BinaryInteger ,但您离满足它的所有要求还差得很远,比如bitWidth: InttrailingZeroBitCount: Intvar words: Words 、所有相关的初始值设定项等。

    您对Numeric的遵守也不完整。 您需要实施var magnitude: Self.Magnitude**=Numeric还改进了AdditiveArithmetic ,因此您需要 unary + 、 binary + 、 unary -和 binary - AdditiveArithmetic还对Equatable了改进,因此您需要==

    不过,这些实际上都不重要,因为您实际上不想符合 BinaryInteger,所以它完全偏离了您想要实现的目标。

您正在寻找的是OptionSet

struct AppState: OptionSet {
    let rawValue: Int32
    
    static let preferences = AppState(rawValue: 1 << 0)
    static let insulinFavorites = AppState(rawValue: 1 << 1)
    static let foods = AppState(rawValue: 1 << 2)
    static let configurations = AppState(rawValue: 1 << 3)

    static let uninitialized: AppState = []
    static let fullyInitialized: AppState = [.preferences, .insulinFavorites, .foods, .configurations]
}

let state: AppState = [.preferences, .foods]

OptionSet提供了一个类似 Set 的 API 来像这样操作位字段,抽象出操作这些值所必需的底层按位操作。

其他一些需要考虑的想法:

  • 如果空间不是问题(在这种规模下,它可能不是),那么一个充满布尔值的结构可能更可取。
  • 如果您的状态变得更加复杂,并且并非所有位组合都有效,那么最好使用枚举 model 每种可能的情况(位组合),并使用 state 机器在这些有效状态之间转换。 这样,无效状态将永远不可能(不会有代表它们的枚举)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM