How to know if a number is odd or even in Swift?
IosSwiftParityIos Problem Overview
I have an array of numbers typed Int
.
I want to loop through this array and determine if each number is odd or even.
How can I determine if a number is odd or even in Swift?
Ios Solutions
Solution 1 - Ios
var myArray = [23, 54, 51, 98, 54, 23, 32];
for myInt: Int in myArray{
if myInt % 2 == 0 {
println("\(myInt) is even number")
} else {
println("\(myInt) is odd number")
}
}
Solution 2 - Ios
Use the %
Remainder Operator (aka the Modulo Operator) to check if a number is even:
if yourNumber % 2 == 0 {
// Even Number
} else {
// Odd Number
}
or, use remainder(dividingBy:)
to make the same check:
if yourNumber.remainder(dividingBy: 2) == 0 {
// Even Number
} else {
// Odd Number
}
Solution 3 - Ios
Swift 5 adds the function isMultiple(of:)
to the BinaryInteger
protocol.
let even = binaryInteger.isMultiple(of: 2)
let odd = !binaryInteger.isMultiple(of: 2)
This function can be used in place of %
for odd/even checks.
This function was added via the Swift Evolution process:
- Preliminary Discussion in Swift Forum
- Swift Evolution Proposal
- Accepted Swift Evolution Implementation
Notably, isEven
and isOdd
were proposed but not accepted in the same review:
> Given the addition of isMultiple(of:)
, the Core Team feels that isEven
and isOdd
offer no substantial advantages over isMultiple(of: 2)
.
>
> Therefore, the proposal is accepted with modifications. isMultiple(of:)
is accepted but isEven
and isOdd
are rejected.
If desired, those methods can be added easily through extension:
extension BinaryInteger {
var isEven: Bool { isMultiple(of: 2) }
var isOdd: Bool { !isEven }
}
Solution 4 - Ios
"Parity" is the name for the mathematical concept of Odd and Even:
> https://en.wikipedia.org/wiki/Parity_(mathematics)
You can extend the Swift BinaryInteger
protocol to include a parity
enumeration value:
enum Parity {
case even, odd
init<T>(_ integer: T) where T : BinaryInteger {
self = integer.isMultiple(of: 2) ? .even : .odd
}
}
extension BinaryInteger {
var parity: Parity { Parity(self) }
}
which enables you to switch
on an integer and elegantly handle the two cases:
switch 42.parity {
case .even:
print("Even Number")
case .odd:
print("Odd Number")
}
Solution 5 - Ios
You can use filter
method:
let numbers = [1,2,3,4,5,6,7,8,9,10]
let odd = numbers.filter { $0 % 2 == 1 }
let even = numbers.filter { $0 % 2 == 0 }