Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public struct OptionSetIterator<Element: OptionSet>: IteratorProtocol where Element.RawValue == Int {
private let value: Element
init(element: Element) {
self.value = element
}
private lazy var remainingBits = value.rawValue
private var bitMask = 1
public mutating func next() -> Element? {
while remainingBits != 0 {
defer { bitMask = bitMask &* 2 }
if remainingBits & bitMask != 0 {
remainingBits = remainingBits & ~bitMask
return Element(rawValue: bitMask)
}
}
return nil
}
}
extension OptionSet where Self.RawValue == Int {
public func makeIterator() -> OptionSetIterator<Self> {
OptionSetIterator(element: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment