Nerd For Tech
Published in

Nerd For Tech

Feel and Make the Arrays more powerful in iOS Development

Photo by Mohamad Mahdi Abbasi on Unsplash

Before writing the custom functions, let us re-visit the available inbuilt functions which are comparatively less used but powerful.

Range Operator As Index

we can use open range or closed range operator to access and modify elements inside array. If the array can't accommodate change then it will throw error.

var array = [1,2,3]array[0…1] = [2,2]
print(array[0..4]) // error: Index Out Of Range

Enumerated

enumerated() will return a pair which has index and element in each iteration.

array.enumerated().forEach({print(“\($0) -> \($1)”)})

ElementsEqual

Compare each and every element inside two arrays based on index and return true only if all elements at respective indexes are equal. This is same as array == arrayCopy.

array.elementsEqual(arrayCopy)

Prefix

if we want to take first ‘n’ elements from the array and not sure of array size then we can use prefix. This will return specified number of elements if available. But if number exceeds the length of array then it will return full array.

array.prefix(20)var test:[Int] = []print(test.prefix(10)) // []

FirstIndex/LastIndex

firstIndex(of: ) or lastIndex(of: ) are used commonly to know the index of element. But there is also firstIndex(where: ) or lastIndex(where: ) which are more powerful. We can use custom predicate to find the index as follows.

//Finding first number which is greater than 2array.firstIndex(where: {$0 > 2})//Finding first empty string in a listarrayNames.firstIndex(where: {$0.isEmpty})

SwapAt

To swap elements inside array, we can use swapAt(from_index, to_index).

array.swapAt(0, 1)

Extension

Now Let’s give more power to Arrays

Replace Occurrences

When we need to replace an element with others we can make use of this extension

extension Array { mutating func replaceOccurrences(of value: Element, with val:    
Element) where Element: Equatable {
var ex = false while ex == false { if let i = self.firstIndex(of: value ) { self[i] = val } else { ex = true }
}
}
mutating func replaceFirstOccurence(of value: Element, with val:
Element) where Element: Equatable {
if let i = self.firstIndex(of: value ) { self[i] = val }
}
mutating func replaceLastOccurence(of value: Element, with val:
Element) where Element: Equatable {
if let i = self.lastIndex(of: value ) { self[i] = val }
}
}

Unique Elements

It is always useful to have information about unique elements in an array. Following will be useful in that case.

extension Array {  func unique() -> [Element] where Element: Equatable {     var newArray: [Element] = []     self.forEach { i in        if !newArray.contains(i) {            newArray.append(i)        }     }     return newArray  }  func uniqueElementsCount() -> [Element : Int] where Element: 
Equatable {
var newArray: [Element:Int] = [:] self.forEach { i in if !newArray.keys.contains(i) { newArray[i] = 0 } else { newArray[i] = (newArray[i] ?? 0) + 1 } } return newArray }}

Count of element

When you need to know how many times an element appeared inside array, use the following snippet

extension Array {  func countOf(element: Element) -> Int where Element: Equatable {    var ex = 0    self.forEach { i in      if i == element {        ex = ex + 1      }    }    return ex  }}

Grouping Strings

When you are having array of names and you want to group them by starting alphabet, go for following extension.

extension Array {func grouped() -> [(alphabet: Character, values: [String])] where 
Element == String {
return Dictionary(grouping: self) { (country) -> Character in return country.first ?? "-" } .map({(alphabet: $0, values: $1)}) .sorted(by: {$0.alphabet < $1.alphabet}) }}

Common Mistake we do unintentionally

There is one common mistake I do unknowingly with arrays is trying to append a element of different data type.

var arr = [1,2,3]
arr.appennd("four") // Not possible

Best work-around is to make array anonymous with ‘Any’

var arr: [Any] = [1,2,3]
arr.append("four")

That’s it..

Thanks for reading…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sai Durga Mahesh

Sai Durga Mahesh

73 Followers

Using Data Science to provide better solutions to real word problems