Power of Two Check Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn your Bit Manipulation question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Power of Two Check runs in O(1) time and O(1) space, in Swift as in every other language.
- ✓FixedWidthInteger gives every integer type nonzeroBitCount, leadingZeroBitCount, trailingZeroBitCount and bitWidth, all in the standard library with nothing to import, so n > 0 && n.nonzeroBitCount == 1 is the direct test.
- ✓Reviewers want one function generic over FixedWidthInteger rather than five copies for Int, UInt, Int32 and friends, and they want the argument label suppressed with an underscore for a predicate this small.
- ✓The Swift trap: Swift traps on integer overflow in release builds too, not only in debug: it is a language guarantee, the single exception being -Ounchecked, which strips the checks and makes the overflow undefined behaviour rather than a trap.
- ✓Int is a value type with no reference counting, so on a concrete type the whole test is register work and nonzeroBitCount inlines to a single ctpop instruction.
What Power of Two Check actually is
Power of Two Check in Swift: what you actually reach for
Swift implementation
// &- is the masking subtract: Swift traps on plain overflow in release too.
func isPowerOfTwo<T: FixedWidthInteger>(_ n: T) -> Bool {
return n > 0 && n & (n &- 1) == 0
}
func isPowerOfTwoPopcount<T: FixedWidthInteger>(_ n: T) -> Bool {
return n > 0 && n.nonzeroBitCount == 1
}
print(isPowerOfTwo(1024)) // true
print(isPowerOfTwo(UInt8(128))) // true
print(isPowerOfTwo(Int.min)) // false, the n > 0 guard
print(Int.min.nonzeroBitCount) // 1 -- why that guard is required
print(1024.trailingZeroBitCount) // 10
print(UInt8(128).leadingZeroBitCount) // 0
print(Int.bitWidth) // 64 on a 64-bit target
// Inspect the overflow instead of trapping on it:
let zero: UInt = 0
let r = zero.subtractingReportingOverflow(1)
print(r.partialValue, r.overflow) // 18446744073709551615 true
// The payoff: a power-of-two capacity replaces modulo with a mask.
let capacity = 1024
print(7777 & (capacity - 1)) // 609, the same as 7777 % 1024
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Power of Two Check?
FixedWidthInteger gives every integer type nonzeroBitCount, leadingZeroBitCount, trailingZeroBitCount and bitWidth, all in the standard library with nothing to import, so n > 0 && n.nonzeroBitCount == 1 is the direct test. There is no isPowerOfTwo property. The masking operators &-, &+ and &* opt out of overflow trapping, and the reporting forms such as subtractingReportingOverflow(_:) return a (partialValue, overflow) tuple when you want to inspect instead of crash. UInt(bitPattern:) reinterprets, while Int(exactly:) returns nil when the value does not fit.
What is the most common Swift mistake when implementing Power of Two Check?
Swift traps on integer overflow in release builds too, not only in debug: it is a language guarantee, the single exception being -Ounchecked, which strips the checks and makes the overflow undefined behaviour rather than a trap. The trap is a fatal process error that do/try/catch cannot intercept, so there is no way to recover at the call site. A hand-rolled n - 1 on UInt(0), or on Int.min, terminates the process rather than returning a wrong answer. The remedy is a different operator token, n &- 1, which wraps deliberately, or subtractingReportingOverflow(1), which hands you the overflow flag. Note also that Int.min.nonzeroBitCount is 1, so the popcount form still needs its n > 0 guard.
How does Power of Two Check actually perform in Swift?
Int is a value type with no reference counting, so on a concrete type the whole test is register work and nonzeroBitCount inlines to a single ctpop instruction. The cost appears when the generic version crosses a module boundary: without @inlinable, or without whole-module and cross-module optimisation enabled, a call constrained to FixedWidthInteger dispatches through a protocol witness table, so you pay an indirect call per test. Boxing an Int into Any or into [Any] allocates an existential and hands ARC traffic back to you. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.