OneBite.Dev - Coding blog in a bite size

Find The Product Of All Elements In An Array In Swift

Code snippet for how to Find The Product Of All Elements In An Array In Swift with sample and detail explanation

Working with arrays is a common programming task, whether for sorting data or performing calculations. This article will demonstrate how to find the product of all elements in an array using Swift.

Code snippet for Finding The Product Of All Elements In An Array

Here is a Swift function that finds the product of all elements in an array:

func productOfArray(_ arr: [Int]) -> Int {
    return arr.reduce(1, *)
}

You can call this function with an array of integers like so:

let array = [2, 3, 4]
let product = productOfArray(array)
print(product)  // Outputs: 24

Code Explanation for Finding The Product Of All Elements In An Array

In the above Swift program, we have defined a function productOfArray that takes an array of integers as an argument.

The main function we are using to calculate the product of all elements in the array is reduce. The reduce function is a higher-order function in Swift that combines all items in a collection to create a single new value.

The reduce function takes two arguments: 1 and *. The initial value is 1 because it’s the identity element for multiplication - any number multiplied by 1 remains the same. We use * as the second argument to reduce because we want to multiply all the elements together.

So the expression arr.reduce(1, *) will multiply together all the numbers in arr, starting with 1.

In the next part of the code, we created an array named array and populated it with the values 2, 3 and 4. We then called the productOfArray function, passing in array as the argument. The function then returns the product of all the elements (2 * 3 * 4), which is 24. We printed the output which showed the expected result: 24.

This method can be used to find the product of all elements in any integer array. This simple, concise method takes advantage of Swift’s powerful, built-in reduce function to solve the problem.

swift