Feel and Make the Arrays more powerful in iOS Development

Sai Durga Mahesh
May 9 · 3 min read
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.

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.

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.

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.

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.

array.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).

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

 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.

  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

  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.

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.

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

That’s it..

Thanks for reading…

Nerd For Tech

From Confusion to Clarification

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/. Don’t forget to check out Ask-NFT, a mentorship ecosystem we’ve started

Sai Durga Mahesh

Written by

Love playing with data

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/. Don’t forget to check out Ask-NFT, a mentorship ecosystem we’ve started

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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