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

Thursday, 12 January 2017

Sort Array in swift


To sort an array we can use sort() which all arrays have in default. We can use sort() and sorted() to sort an array.

To sort an simple array like this, we can use sort() as:

var arr =  [ "orange","Apple" "Grapes","banana"]

arr.sort()


To sort an array of custom object like custom struct or class we  use sort() using a trailing closure that sort an array on field we specify.

For example: We have an array of custom object Opportunity which have a string field date . So to sort this array on date field, here we will first convert string date to Date object . Let's have a look on below code:To sort arrOpportunities on a string field say title,

arrOpportunities.sort{

$0.title.compare($1.title) == NSComparisonResult.OrderedAscending
}

 If we have title say:
["hello","ok","arm","Basket"]  then using  above code will results in

["Basket","arm","hello","ok"]

To get results in ignoring the case we can use localizedCompare() like this:

arrOpportunities.sort{

$0.title.localizedCompare($1.title) == NSComparisonResult.OrderedAscending
}

will result in
["arm","Basket","hello","ok"]

If we want to return an array after doing sort we can use sorted() like this

var arr_sorted =  arrOpportunities.sorted{

$0.title.localizedCompare($1.title) == NSComparisonResult.OrderedAscending
}