Swift Algorithm: How to Multiply Only the Odd Numbers in an Array
How to Get the Odd Numbers Only in Swift
Chances are, you may encounter this kind of issue either in your professional tasks or during a coding examination.
Create a function that multiplies only the odd numbers in an array of integers. The function accepts two parameters: one for the array of integers and the other for the number by which the odd numbers will be multiplied. It will then return the result as an array of integers.
Let’s start by warming up and preparing what the function should look like.
func multiplyOdd(inputList: [Int], multiplyBy: Int) -> [Int] {
}
The first step is to filter the array to remove all even numbers. Since ‘filter’ has already been mentioned, that’s the method we’ll employ.
Swift filter(_:)
In Swift, the filter
method is used to create a new array that contains only the elements of an existing array that meet a certain condition. It works by applying a closure (a block of code) to each element of the original array. This closure returns a Boolean value (true
or false
). If the closure returns true
, the element is included in the new array; if it returns false
, the element is excluded.