The product of an array in Swift (and other programming languages) is the result of multiplying all the elements of the array together. For example, the product of [2, 3, 4]
is 2 * 3 * 4 = 24
. This practical, code-centric article will walk you through 3 different ways to calculate the product of a given array in Swift.
Using a for loop
You can use a for
loop to iterate over the array and update a variable that stores the current product:
let array = [2, 3, 4, 5, 9, 10, 11, 12, 13, 14, 15]
var product = 1
for number in array {
product *= number
}
print(product)
Output:
3891888000
Using the reduce() method
The reduce()
method of the Array
class takes an initial value and a closure that combines each element of the array with the previous result and returns the final result. In the context of this tutorial, you can use it like so:
let array = [2, 3, 4, 8, 9, 10, 11, 12, 13]
let product = array.reduce(1) { $0 * $1 }
print(product)
Output:
29652480
Using the map() and joined(separator:) methods
What we will do is to use the map()
and the joined(separator:)
methods of the Array
class to convert each element of the input array to a string, then join them with a multiplication sign as a separator and evaluates the resulting expression using NSExpression
.
Example:
import Foundation
let array = [2, 3, 4, 5, 6]
let expression = array.map(String.init).joined(separator: "*")
let product = NSExpression(
format: expression).expressionValue(with: nil, context: nil) as! Int
print(product)
Output:
720
I put this approach here just for your reference. It is not very efficient or elegant. It involves converting each element of the array to a string, concatenating them with a multiplication sign, and then parsing and evaluating the resulting expression using NSExpression
. This makes a lot of unnecessary string manipulation and computation that can be avoided by using other solutions.