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?
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?
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")
}
}
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
}
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:
Notably, isEven
and isOdd
were proposed but not accepted in the same review:
Given the addition of
isMultiple(of:)
, the Core Team feels thatisEven
andisOdd
offer no substantial advantages overisMultiple(of: 2)
.Therefore, the proposal is accepted with modifications.
isMultiple(of:)
is accepted butisEven
andisOdd
are rejected.
If desired, those methods can be added easily through extension:
extension BinaryInteger {
var isEven: Bool { isMultiple(of: 2) }
var isOdd: Bool { !isEven }
}
"Parity" is the name for the mathematical concept of Odd and Even:
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")
}
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 }