73

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?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Asif Bilal
  • 4,309
  • 3
  • 17
  • 27

5 Answers5

141
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")
  }
}
Mihriban Minaz
  • 3,043
  • 2
  • 32
  • 52
Charith Nidarsha
  • 4,195
  • 3
  • 28
  • 32
  • Oh Sorry! yes it's dead straight. Actually, while coding i had an compile error in the above code. Due to which it was showing me errors on the line (Where i was using % and / operators) as well. – Asif Bilal Jun 06 '14 at 13:46
  • 2
    Here's a functional approach: let numbers = [0, 1, 2, 3] let evenNumbers = numbers.filter { $0 % 2 == 0 } let oddNumbers = numbers.filter { $0 % 2 != 0 } – Karoly Nyisztor Aug 03 '18 at 08:45
  • I'm using this with .isHidden, such as `img1.isHidden = pageNumber % 2 == 0` and `img2.isHidden = pageNumber % 2 != 0` – Mike Irving Jun 17 '19 at 11:29
36

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
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
num8er
  • 18,604
  • 3
  • 43
  • 57
  • 3
    Well there is better and much faster way to do it using AND (&) operator let inputArray = [23,25,2,4,9] for x in inputArray { if ( x&1 == 1) { print ("odd") } else { print ("even") } } – i.AsifNoor Sep 19 '17 at 14:09
  • 1
    @i.AsifNoor I agree with You. But modulus (getting rest from division) operation has same code in all languages. – num8er Sep 19 '17 at 16:16
  • 3
    SHORT WAY extension Int { func isEven() -> Bool { return (self % 2 == 0) } } – Prabhjot Singh Gogana Dec 18 '17 at 06:56
  • 2
    **Still shorter**: `extension Int { var isEven: Bool { return (self % 2 == 0) } } ` – Reinhard Männer Oct 29 '18 at 09:54
  • 1
    :D stupidity. You mean to create `isEven` method as extension of `Int` type. But overall You've to check if it's odd or even. So You'll use `if ... else...` with `isEven` method. So where is shortening? In fact if You'll just once why do abstraction on primitives? What's gain? – num8er Oct 29 '18 at 10:39
  • @ReinhardMänner seems like people forgot about such methods like: https://developer.apple.com/documentation/swift/double/2884269-remainder – num8er Oct 29 '18 at 10:47
  • @num8er: If you have to do such checks often, then it is indeed shorter to write `anyInt.isEven` as `(anyInt % 2 == 0)`. In any way, it is clearer. And the link that you provided applies to `Double`, not to `Int`. Do you really think that applying `remainderReportingOverflow(dividingBy other: Int) -> (partialValue: Int, overflow: Bool)` to an `Int` is better than what I suggested? – Reinhard Männer Oct 29 '18 at 12:12
  • 1
    @ReinhardMänner I'm not saying what is better or not. I'm saying mostly it's being happened once in an app. So we are talking about same things but with different words. – num8er Oct 29 '18 at 13:48
25

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 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 }
}
Community
  • 1
  • 1
pkamb
  • 33,281
  • 23
  • 160
  • 191
6

"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")
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
3

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 }
Mohammad Reza Koohkan
  • 1,656
  • 1
  • 16
  • 36