Thursday 19 January 2017

Operation on Collection in Swift

In iOS app development we need to perform some task on collection (Array,dictionary..) in swift. For example to get the sum of the element in an array we could go for for-in loop . Do code like this:

let arr =  [1,3, 4,6,9]

var sum = 0
for i in arr{
sum += i
}

We can achieve such kind of task very easily with a line of code.

Working with Map, filter, reduce and flatMap:

To get the sum of all element we can write

let sum =  arr.reduce(0,+)

Map:

We use map to  loop over the collection and apply a same  on each element in collection. For example to get the square of of each element in an array we could go for for in loop and to square of each element in an array.

With map, we can do this task this way:
let arr = [1,2,4,5,6,7,8,9]

let squares =  arr.map{$0 * $0}

The map function has a single argument which is a closure. Map function calls this closure as it loop over the collection. This closure takes an element from the collection as an argument and returns result. The map function return the result in an array.

We can  write above line of code as:

let squares2 =  arr.map{element in   element * element}

The keyword  in separates  the argument from the body of the closure .

The map operation can be performed on each collection type it is not limited to just an array. We can use this with dictionary, set also. But the result of the operation is always an array.

Filter: We use filter where we want to filter the collection  of data with a condition. Filter function loop over the collection  and returns only those element from the collection which satisfy  a given condition in include.

let arrData  = [1,23,45,,4,6,8,3]

For example : To get only those element from above array which is even, we write:

let arrEven = arrData.filter{ $0 %2 == 0}

Reduce: reduce method used to combine all elements in a collection to create a single value . The reduce() method takes two arguments, an initial value and a closure

let  fullStatement  = arr.reduce("==") {text, name in "\(text),\(name)"}

FlatMap: Used to flatten to  collection of   collections.

let complexArray  = [[2,3,5],[34,56], [34,56,78]]

let flat =  complexArray.flatMap {$0 }

The above line of code will combine all sub array  from complexArray into  a single array.

With flatMap and  chaining of the above methods we can solve complex queries on collection .

For example: get all even elements from complexArray

let   evenNums  = complexArray.flatMap{ 
                  subArray in subArray.filter{ $0 %2 == 0}
             }

In short form we can write above line as:
let evenInShortForm =  complexArray.flatMap { $0.filter{ $0 %2 == 0  }}

References:http://useyourloaf.com

No comments:

Post a Comment