Parity 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 this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Parity Check runs in O(1) time and O(1) space, in Swift as in every other language.
- ✓nonzeroBitCount is a property on every FixedWidthInteger (UInt64, Int, UInt8 and the rest), returns Int, and needs no import because it is in the standard library; parity is x.nonzeroBitCount & 1.
- ✓Reviewers want one function generic over T: FixedWidthInteger (often further constrained to UnsignedInteger) instead of five width-specific copies, and @inlinable on it if it ships in a package other modules import, because otherwise the generic call is not specialised across the module boundary.
- ✓The Swift trap: Swift's << and >> are smart shifts. Over-shifting produces 0 or the sign fill, which Go and Python also do, unlike Java and C# (which mask the count) or Rust (which panics in debug).
- ✓nonzeroBitCount is built on Builtin.int_ctpop, so it becomes CNT plus ADDV on arm64 and a POPCNT on x86 where the feature is present: no call at all.
What Parity Check actually is
Parity Check in Swift: what you actually reach for
Swift implementation
import Foundation
@inlinable
public func parity<T: FixedWidthInteger>(_ x: T) -> Bool {
x.nonzeroBitCount & 1 == 1
}
/// Branch-free fold. Masking shifts so an out-of-range distance
/// can never silently reverse direction.
public func parityFold(_ value: UInt64) -> UInt8 {
var x = value
x ^= x &>> 32
x ^= x &>> 16
x ^= x &>> 8
x ^= x &>> 4
return UInt8((0x6996 as UInt16) >> UInt16(x & 0xF) & 1)
}
public func parity(of bytes: Data) -> Bool {
bytes.reduce(UInt8(0), ^).nonzeroBitCount & 1 == 1
}
assert(parity(0b1011 as UInt8))
assert(!parity(UInt64.max)) // 64 ones, even
assert(parityFold(UInt64.max) == 0)
assert(parityFold(1) == 1)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 Parity Check?
nonzeroBitCount is a property on every FixedWidthInteger (UInt64, Int, UInt8 and the rest), returns Int, and needs no import because it is in the standard library; parity is x.nonzeroBitCount & 1. Its companions are leadingZeroBitCount, trailingZeroBitCount, bitWidth, byteSwapped, and the masking/wrapping operators &<<, &>>, &+. For a buffer: data.reduce(UInt8(0), ^).nonzeroBitCount & 1, or withUnsafeBytes to walk it in UInt64 chunks.
What is the most common Swift mistake when implementing Parity Check?
Swift's << and >> are smart shifts. Over-shifting produces 0 or the sign fill, which Go and Python also do, unlike Java and C# (which mask the count) or Rust (which panics in debug). What is Swift's alone is the other half: a NEGATIVE shift count reverses direction, so x << -2 genuinely evaluates x >> 2 and compiles without a warning. A fold whose distance is computed as bitWidth - k therefore runs backwards, silently, the moment k exceeds the width, instead of trapping or masking. &<< and &>> give the C behaviour. Separately, ordinary arithmetic traps on overflow at run time, so summing popcounts near the top of a small type needs &+.
How does Parity Check actually perform in Swift?
nonzeroBitCount is built on Builtin.int_ctpop, so it becomes CNT plus ADDV on arm64 and a POPCNT on x86 where the feature is present: no call at all. The Swift-specific cost is generics. A func parity<T: FixedWidthInteger> called from another module dispatches through a witness table unless it is @inlinable or the build enables cross-module optimisation, turning a two-instruction body into an indirect call. Value types like UInt64 are not refcounted, but boxing one into Any or an existential allocates and adds ARC traffic. 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 trialBefore paying full price for a tool, check the student deals on AI and developer tools listed 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.