Swift Array and it’s Higher Order Functions

Author - Nishita

Code optimization is necessary to improve the code efficiency and quality. Here in this article, you will learn about the reduce code using Higher order functions like Map, Filter, Reduce, flatMap, etc… In Swift, you can use Map, Reduce and Filter to loop over collection types like array and dictionary without using a for loop. Here are some examples of the Array Functions which help to reduce the code and loops.

USING MAP FUNCTION

We generally use a for loop to iterate through every number and do the operations. While Map function iterates over every item in a collection and applies an operation to each element in the collection.

Before using map function, let’s try to understand how to use map and it’s syntax with each field and it’s meaning in short.

let arrMap = arrOfOpration.map { (result) -> Int in
    return result * 10
}
let arrMap = arrOfOpration.map { $0 * 10 } //map on int array
print(arrMap) // it will print [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]

In above two approaches, The second approach is very concise because as now the return clause has been removed, input parameter and return type of the operations are going performed inside so we don’t worry about that.

Let’s take a differentiate between Map and for-in loop

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50] // array of Int

▪ First we multiply by 10 to every elements using for-in loop :

var newArr: [Int] = [] //for-in loop
for value in arrOfOpration {
    newArr.append(value*10)
}
print(newArr)

▪ Now, we multiply by 10 using the map function (shortest version of For-in loop)

let arrMap = arrOfOpration.map { $0 * 10 } //map on int array
print(arrMap) // it will print [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]

What happens here?

    • First a constant arrOfOpration is defined of type array, and initialised with a random values.
    • Then function map is called on the constant arrOfOpration, the function has one argument, which multiply values by 10
    • Finally, the result is print.

The map function returns these results in an array. It will also work with string array.

USING FILTER FUNCTION

A filter is used to loop over an every item in the array and return an array containing only those values which satisfy an include condition. The filter is a very useful operation which allow us to filter the existing elements and filter out based on our requirements.

Filter method has a single argument that specifies the include condition. This function takes as argument from the array and return a bool if the item should be included in the result.

Syntax :- arrOfOpration.filter(isIncluded: (Int) throws -> Bool)

Filter function calls a closure called isIncluded which takes one Int as an argument and returns a Bool. So, the isIncluded closure will return a bool value for each collection item and based on this result a new filtered array will be generated.

Let’s understand with an example :-

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Now, apply a filter on arrOfOpration which integers returning only the odd values.

let arrFilter = arrOfOpration.filter{(arrOfOpration) -> Bool in
    arrOfOpration % 2 != 0
}
print(arrFilter) // it will print [1,3,5]

▪ You can also set the expressions above return a Boolean, you can assume that the closure for filter needs to return a bool, and then only returns an array of values that passed the condition, i.e returned true.

let even = arrOfOpration.filter({ (value:Int)  Bool in
    return value % 2 == 0 
})
print(even)	// it will print [2, 4, 10, 20, 30, 40, 50]

⁃ The expression arrOfOpration % 2 == 0  integers uses the remainder operator % to figure out whether element is divisible by 2 or not. We can identify the number is even when the remainder of operation is 0.

⁃ Filter method has a single argument that specifies the include condition. This function takes as argument from the array and return a bool if the item should be included in the result.

⁃ It will also work with string array.

USING REDUCE FUNCTION

Returns the result of combining the elements of the sequence using the given closure. It loops over every item in an array and combines into one value. It reduces the result from an array of elements to a single most probably a computed value from the collection.

-Simply it convert multiple values into one value.

Syntax :-

func reduce<result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

OR

let arrReduce = numbers.reduce(0) {$0 + $1}

OR

let reduce = numbers.reduce(0,*)

 

Let’s understand with an example

▪ Suppose we have an array of integers

 

 

 

 

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Now, reduce with an addition operation

let arrReduce = arrOfOpration.reduce(0, {x,y in
    x+y
})
print(arrReduce) // it will print 165

▪ Initial value is 0,  x is 0, y is 1, and it returns x+y so, result or initial value will be 1,
now Initial value is 1,  x is 1, y is 2 and it returns x+y so, result becomes 3,
so now x is 3, y is 3 and it returns x+y so, result becomes 6,
now initial value is 6,  x is 6, y is 4 and it returns x+y so, result becomes 10,
so now x is 10, y is 5 and it returns x+y so, result becomes
15, now initial value is 15, x is 15, y is 10 and it returns x+y so, result becomes 25,

Reduce function takes two arguments. One is initial value which is used to store initial value or result returned by the closure from each iteration. And other one is closure which take two arguments, one is initial value or the result from the previous execution of the closure and the other one is next item in the collection.

USING FLATMAP FUNCTION

Flatmap will give us a single set of element and it will remove unnecessary element as well. If we have two arrays within an array then it will combine into a single array. Flatmap resulting returns an array.

Syntax :- func Flatmap(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence

Let’s understand with an example

▪ Suppose we have an array of strings

let arrOfOprationString = ["SWIFT","Array"]

▪ Now, apply a flatmap operation on arrOfOprationString

let arrFlaten = arrOfOprationString.flatMap{return $0}
print(arrFlaten) // it will print [“S”, “W”, “I”, “F”, “T”, “A”, “r”, “r”, “a”,”y”]

▪ Now, apply a flatmap operation on array within an array

let arrWithInArr = [[10,25,30],[45,50]]
let arrFlaten = arrWithInArr.flatMap{(array)in
    return array
}
print(arrFlaten) // it will print [10,25,30,45,50]

First apply a function to all strings and flatten all the sub element into a single collection. And also it removes the nil value.

CONTAINS ELEMENTS

It will return a value indicating whether the sequence contains an element that satisfies given predicate. Suppose we have two arrays and find the same value in both arrays than is contained is used.

Let’s understand with an example

▪ Suppose we have an two arrays

let arr1 = [1,2,3,4,5]
let arr2 = [3,4,5,6,7]

▪ Now, If you want a value which contains in both arrays arr1 and arr2

let arrSimilar = arr1.filter(arr2.contains)
print(arrSimilar) // it will print [3,4,5]

▪ Suppose we have an two string arrays

let arr1 = ["Swift","Array","YES"]
let arr2 = ["Swift","Array"]     
let arrSimilar = arr1.filter(arr2.contains)
print(arrSimilar) // it will print [“Swift”,”Array”]

UNION

It will merge two arrays and returns an array.

Let’s understand with an example

▪ Suppose we have an two arrays

let arr1 = [1,2,3,4,5]
let arr2 = [3,4,5,6,7]

▪ Now, If you want to combine two collection into single

let arrSet1 = Set(arr1)
let arrSet2 = Set(arr2)
let arrUnion = Array(arrSet1.union(arrSet2))
print(arrUnion) // it will print [3,1,4,6,7,2,5]

▪ Suppose we have two string arrays

let arr1 = ["Swift","Array","YES"]
let arr2 = ["Swift","Array”]
let arrSetString1 = Set(arrString1)
let arrSetString2 = Set(arrString2)
let arrUnionString = Array(arrSetString1.union(arrSetString2))
print(arrUnionString) // it will print [“Swift”,”Array”,”YES”]

INTERSECTION

It will merge two arrays and returns an array. Returns a value that similar in both collection and returns an array

Let’s understand with an example :-

▪ Suppose we have two arrays

let arr1 = [1,2,3,4,5]
let arr2 = [3,4,5,6,7]

▪ Now, If you want to combine two collection into single

let arrIntersection1 = Set(arr1)
let arrIntersection2 = Set(arr2)
let arrInter = Array(arrIntersection1.intersection(arrIntersection2))
print(arrInter) // it will print [3,4,5]

▪ Suppose we have two string arrays

let arr1 = ["Swift","Array","YES"]
let arr2 = ["Swift","Array"]
let arrIntersecStr1 = Set(arrString1)
let arrIntersecStr2 = Set(arrSetString2)
let arrInterstring = Array(arrIntersecStr1.intersection(arrIntersecStr2))
print(arrInterstring) // it will print ["Swift", "Array"]

ADDING ELEMENTS

It is similar as contains.

Let’s understand with an example

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Now insert an element 111, 222, 333 at index 3

arrOfOpration.insert(contentsOf: 100...103, at: 3) // it will print [1,2,3,111,222,333,4,5,10,20,30,40,50]

If you want to insert a single element then also you can insert

APPEND

It will add a new element at the end of collection. And it will append a single element to the end of array.

Let’s understand with an example

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Now add an element 85 :

arrOfOpration.append(85) // it will print [1,2,3,4,5,10,20,30,40,50,85]

INSERT AT

It will insert a new element at a specific position of existing element. Index must be a valid index of the array.

Let’s understand with an example

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Now insert an element 100 at index 3

arrOfOpration.insert(100, at: 3) // it will print [1, 2, 3, 100, 4, 5, 10, 20, 30, 40, 50]

SUBSCRIPT ELEMENTS

It will accesses the element at the specific position.

Let’s understand with an example

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Now we need an element at index 5

print(arrOfOpration[5]) // it will print 10

▪ If you want to access a first element of an array

if let firstNumber = arrOfOpration.first {
    print(firstNumber) // it will print 1
}

▪ If you want to access a last element of an array

if let lastNumber = arrOfOpration.last {
    print(lastNumber) // it will print 50
}

▪ If you want to access elements within a range of an array

let arrRange = arrOfOpration[2 ..< arrOfOpration.endIndex]
print(arrRange) // it will print [3,4,5,10,20,30,40,50]

▪ If you want to access elements randomly

let arrRandom = arrOfOpration.randomElement()!
print(arrRandom) // it will print any random number of the collection

REPLACE  ELEMENTS

It will replace the new element to the existing element in collection.

Let’s understand with an example

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Now we replace an element at index 3

arrOfOpration[3] = 19
print(arrOfOpration) // it will print [1,2,3,19,5,10,20,30,40,50]

▪ If you want to replace range of an array

arrOfOpration.replaceSubrange(Range(1...2), with: [7,7])
print(arrOfOpration) // it will print [1,7,7,19,5,10,20,30,40,50]

REMOVE  ELEMENTS

It will remove and return the element at the specific position.

Let’s understand with an example

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Now we remove an element at index 5

let arrRemove = arrOfOpration.remove(at: 5)
print(arrRemove) // it will print [1,2,3,4,5,20,30,40,50]

▪ Now if you want to remove first element of an array

let arrRemoveFirst = arrOfOpration.removeFirst()
print(arrRemoveFirst) // it will print [2,3,4,5,10,20,30,40,50]

▪ If you want to remove last element of an array

let arrRemoveLast = arrOfOpration.removeLast()
print(arrRemoveLast) // it will print [1,2,3,4,5,10,20,30,40]

▪ If you want to remove element within a range of an array

arrOfOpration.removeSubrange(1..<4)
print(arrOfOpration) // it will print [1,10,20,30,40,50]

REVERSE ELEMENTS

It returns the elements of an array in reverse order.

Let’s understand with an example

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Apply a reverse function on arrOfOpration

let arrReverse = Array(arrOfOpration.reversed())
print(arrReverse) // it will print [50,40,30,20,10,5,4,3,2,1]

COUNT ELEMENTS

It returns the number of elements present in collection.

Let’s understand with an example

▪ Suppose we have an array of integers

var arrOfOpration = [1,2,3,4,5,10,20,30,40,50]

▪ Now count the number of elements in arrOfOpration

print(arrOfOpration.count) // it will print 10

Don’t miss the next post!

Loading

Related Posts