Created
May 29, 2022 17:07
-
-
Save krzyzanowskim/eacd6964f492ca5f85be4879c588ada5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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