A little bit of Functional Programming in Swift - The Shopping Cart Problem

Subscribe to my newsletter and never miss my upcoming articles

Hello ladies and gentlemen, Leo here.

Today we will explore some Functional Programming with Swift.

The problem:

I have a dictionary representing a Shopping Cart. The cart dictionary sctructure is [Chocolate: Int] where chocolate is a class that has the name of the chocolate and its price, and the Int is the quantity of that item in the Shopping Cart. The problem is sum the total cart value.

So here we have two separate problems. First one we have to transform(map) into simple values and after that we can just sum them.

Let's code.

    let cart = ShoppingCart.sharedCart.cart
    let total =
      cart.map { (key, value)  in
      key.priceInDollars * Float(value) // 1 - here we are mapping each dictionary entry to a float value, and the result is a [Float]
    }.reduce(0, +) // 2 - after having the [Float] we can just simply apply a reduce function to sum them all

Explanation:

1 - The .map returns a array that each row represent how much is the sum of the price of each item in the cart.

2 - The first parameter of reduce is the initial value, this case zero. The second is a function that will be use to reduce de values. In this case + in Swift is a function so we can pass by to sum all the elements and reduce to just ONE, the final sum result.

Done!

Any thoughts will be appreciated!

Thanks for the reading and... That's all folks!

No Comments Yet