[英]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;
你在这里有几个问题:
代码像(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
) .
您正在尝试符合BinaryInteger
,但您离满足它的所有要求还差得很远,比如bitWidth: Int
、 trailingZeroBitCount: Int
、 var 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 来像这样操作位字段,抽象出操作这些值所必需的底层按位操作。
其他一些需要考虑的想法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.