Best performance way to know if a number is even or odd employing Swift
How know if a number is even or odd using low-level operator
IOS DEVELOPMENTSWIFT
Eduardo Domínguez Menéndez
1/20/20251 min read
The standard way to figure out if a number is even or odd is applying the operation %2 but on apps or projects with high intensity of calculations gain time on each operation is critical.
Standard way
As I have just said common way to check if a number is even or odd is:
let isOdd = number % 2
Best performance approach
But there’s a faster approach employing a low-level alternative using the bitwise & operator:
let isOdd = number & 1
On both approaches:
isOdd = 0 → number is even
isOdd = 1 → number is odd
The underlying logic of the bitwise operator for this case
1 in binary is 0001, the bitwise % operation keeps only the least significant bit and this bit represents parity.