How to know if a number is odd or even in Swift?
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
}
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")
}
}