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
}

No comments:

Post a Comment