remove all even numbers from an array in swift

You can remove all even numbers from an array in Swift using the filter method. filter takes a closure that returns a boolean value indicating whether or not the current element should be included in the resulting array. We can use the modulo operator to determine if a number is even.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let oddNumbers = numbers.filter { $0 % 2 != 0 }
print(oddNumbers) // [1, 3, 5, 7, 9]
127 chars
4 lines

In the above code, we declare an array of numbers ranging from 1 to 9 inclusive. We then use the filter method to iterate over the array and only keep the odd numbers. The closure checks if the number is not divisible by 2 with no remainder ($0 % 2 != 0) and returns true for odd numbers.

The resulting oddNumbers array is printed, which only contains the odd numbers from the original numbers array.

gistlibby LogSnag