Swift Array – Filter Odd Numbers

To filter odd numbers from a Swift Array, call filter() method on this array and pass the predicate/condition that the element is odd.

filter() method returns a new array with the numbers of the original array, which are only odd.

Example

In the following program, we will take an array of numbers, and filter only those numbers that are odd.

main.swift

</>
Copy
var arr = [1, 99, 6, 74, 5]
let result = arr.filter { $0 % 2 != 0 }
print("Original Array : \(arr)")
print("Filtered Array : \(result)")

Output

Conclusion

Concluding this Swift Tutorial, we learned how to filter only odd numbers in given integer array in Swift.