我在Swift中有一个自定义的OptionSetType结构。如何枚举实例的所有值?
这是我的OptionSetType:
struct WeekdaySet: OptionSetType { let rawValue: UInt8 init(rawValue: UInt8) { self.rawValue = rawValue } static let Sunday = WeekdaySet(rawValue: 1 << 0) static let Monday = WeekdaySet(rawValue: 1 << 1) static let Tuesday = WeekdaySet(rawValue: 1 << 2) static let Wednesday = WeekdaySet(rawValue: 1 << 3) static let Thursday = WeekdaySet(rawValue: 1 << 4) static let Friday = WeekdaySet(rawValue: 1 << 5) static let Saturday = WeekdaySet(rawValue: 1 << 6) }
我想要这样的东西:
let weekdays: WeekdaySet = [.Monday,.Tuesday] for weekday in weekdays { // Do something with weekday }
在Swift 3中,标准库中没有方法
枚举一个OptionSetType(Swift 2)的元素。
OptionSet(Swift 3)。
原文链接:https://www.f2er.com/swift/320326.html枚举一个OptionSetType(Swift 2)的元素。
OptionSet(Swift 3)。
这是一个简单地检查每一位的可能的实现
的基本原始值,并且对于设置的每个位,
返回相应的元素。
“溢出乘法”& * 2用作左移,因为<仅针对具体的整数类型定义,但不适用于IntegerType协议。 Swift 2.2:
public extension OptionSetType where RawValue : IntegerType { func elements() -> AnySequence<Self> { var remainingBits = self.rawValue var bitMask: RawValue = 1 return AnySequence { return AnyGenerator { while remainingBits != 0 { defer { bitMask = bitMask &* 2 } if remainingBits & bitMask != 0 { remainingBits = remainingBits & ~bitMask return Self(rawValue: bitMask) } } return nil } } } }
使用示例
let weekdays: WeekdaySet = [.Monday,.Tuesday] for weekday in weekdays.elements() { print(weekday) } // Output: // WeekdaySet(rawValue: 2) // WeekdaySet(rawValue: 4)
Swift 3:
public extension OptionSet where RawValue : Integer { func elements() -> AnySequence<Self> { var remainingBits = rawValue var bitMask: RawValue = 1 return AnySequence { return AnyIterator { while remainingBits != 0 { defer { bitMask = bitMask &* 2 } if remainingBits & bitMask != 0 { remainingBits = remainingBits & ~bitMask return Self(rawValue: bitMask) } } return nil } } } }