Skip to content

Instantly share code, notes, and snippets.

@T1T4N
Last active August 9, 2024 09:52
Show Gist options
  • Save T1T4N/b53bdd911a5d0433efae6ecdc970673c to your computer and use it in GitHub Desktop.
Save T1T4N/b53bdd911a5d0433efae6ecdc970673c to your computer and use it in GitHub Desktop.
Add support for manipulating specific bits within an integer by treating it like an array of Bool values
// Source: https://www.douggregor.net/posts/swift-for-cxx-practitioners-extensions/
extension UInt32 {
subscript(index: Int) -> Bool {
get {
(self & UInt32(1) << index) != 0
}
set {
let mask = UInt32(1) << index
self = (self & ~mask) | (newValue ? mask : 0)
}
}
}
// Usage
var flags: UInt32 = 0b1001
flags[2] = true // set bit #2
flags[0] = false // clear bit #0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment