Codementor Events

reduce function in swift

Published Dec 20, 2017

We use reduce function to combine all the items in a collection to create a new value.

In the below example, reduce function takes two parameters, first parameter is a initial value and second parameter is a combine function.

let array = [10,11, 12, 14]
let total = array.reduce(0,+) //47

Calculating average number from a collection:

Double(array.reduce(0, +))/Double(array.count)
Double(array.reduce(0, +)): This will produce sum of all integers in a collection

This will also work with strings using the + operator to concatenate

let stringsArray = ["abc","def","ghi"]
let combinedString = stringsArray.reduce("",  +)//abcdefghi

The combine argument is a closure so you can also write reduce using the trailing closure syntax

let names = ["Saikiran","K"]
let fullName = names.reduce("My Name is: ") {text, name in "\(text) \(name)"}
print(fullName) //My Name is:  Saikiran K

Start writing here...

Discover and read more posts from saikiran
get started
post commentsBe the first to share your opinion
Show more replies