Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Power of Two Check Implementation in Swift

11 min readbeginner
Website QA and SEO audits

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

A power-of-two test asks whether a positive integer has exactly one bit set: 1, 2, 4, 8, 16, and so on. The standard trick is n > 0 combined with n & (n - 1) == 0, because subtracting one flips the lowest set bit and every bit below it, so the AND clears to zero only when there was a single set bit to begin with. Engineers reach for it when sizing hash tables, ring buffers and allocator blocks, where a power-of-two capacity turns an expensive modulo into a cheap mask (i & (cap - 1)), and when validating an alignment argument before handing it to a lower layer.

Power of Two Check in Swift: what you actually reach for

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.

Swift implementation

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. Writing n - 1 instead of n &- 1 draws a comment even behind an n > 0 guard, because the masking operator states the intent at the token level. Converting with Int(someUInt) where the value may not fit is rejected in favour of Int(exactly:) and an explicit nil branch.
swift
// &- 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 Free

The Swift-specific 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. 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.

Performance in Swift, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Power of Two Check between languages.

Real-World Applications

Power of Two Check is used extensively in production software: database engines, compilers, operating systems, and application frameworks all use Power of Two Check internally. In Swift specifically, UIKit, SwiftUI, and Vapor apply these concepts. Understanding Power of Two Check helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Power of Two Check appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Power of Two Check over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Power of Two Check to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Want 50 audits a day? Explore SeekerPro

Engagement

0

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.