Featured Image
Software Development

Mastering Swift arrays: guide to essential operations and techniques

Working with array operations can be challenging for new developers. Oftentimes, they have given nightmares to a few developers in the early stages of their careers. I tried playing around with arrays in Swift to get accustomed to their different operations and collated a few that I would like to share with everyone.

Mastering array operations is paramount for a Swift developer. The following blog post will help you understand the intricacies of Swift arrays. You will also get practical strategies to overcome everyday challenges. This article will enable both a beginner and a seasoned developer. So, let’s begin:

Basics and checks

In Swift programming, arrays are building blocks that enable developers to manage collections of elements with shared data types. This section explores the primary operations and checks performed on Swift arrays.

Array in Swift: A collection of elements

Before diving into the operations, let’s understand what a Swift array is. An array is a collection of data that simplifies the storage and acquisition of similar elements. It helps organize data, which assists in analysis.

Understanding the Swift array prepares you for advanced operations. Let’s explore basic checks and operations to optimize your skills as a Swift developer.

Determine array inclusion of a specific value

You use the ‘contains’ method to find out whether an array has a specific value. Below is an illustration:

let users : [String] = ["abc","def","xyz","pqr"]

func containsUser(withName name: String) -> Bool {
    return users.contains(where: {$0 == name})
}

let isContainUser = self.containsUser(withName: "abc")
debugPrint(isContainUser)

OUTPUT: true

In this example, the containsUser command helps find out if the array has the username “abc” and prints the result. The ‘contains’ method applies the condition using a closure.

Finding the index of an element 

Another useful operation is to find the index of an element in an array. You can do so using the firstIndex method.

let users : [String] = ["abc","def","xyz","pqr"]

func findIndex(ofUser user: String) -> Int {
    return users.firstIndex(of: user) ?? 0
}

let indexOfUser = self.findIndex(ofUser: "xyz")
debugPrint(indexOfUser)

OUTPUT: 2

In this illustration, the findIndex command ascertains the index of the username “xyz” in the array. The firstIndex method gives an optional and uses the nil-coalescing operator (??) to give a default value of zero if the username doesn’t exist.

Discovering matching elements 

You can use compactMap command to fetch elements meeting a specific condition from an array. Using these elements, you can create a new one.

let users : [String] = ["avc","def","xyz","pqr","xyz"]

func findMatching(name: String) -> [String] {
    return users.compactMap {$0 == name ? $0 : nil}
}

let matchingArray = self.findMatching(name: "xyz")
debugPrint(matchingArray)

OUTPUT: ["xyz", "xyz"]

In this illustration, the findMatching command creates a new array (matchingArray) filled with elements from users with the name “xyz”. The closure in compactMap enforces the condition and either returns the element or nill.

Fetch all matching elements with their index

To find the matching elements with their indices, use the enumerated command. It permits you to iterate over the elements and their indices.

let users : [String] = ["abc","def","xyz","pqr","xyz","xyz"]

func findMatchingElementsWithIndex(name: String) -> [(String,Int)] {
      var result : [(String,Int)] = []
      for(index,value) in users.enumerated() {
            if value == name {
                result.append((value,index))
            }
      }
      return result
}

let matchingElements = self.findMatchingElementsWithIndex(name: "xyz")
debugPrint(matchingElements)

OUTPUT: [("xyz", 2), ("xyz", 4), ("xyz", 5)]

This illustration showcases the findMatchingElementsWithIndex function. Using the enumerated function, you can iterate over each element and its index in the array users. Matched elements and their indices are stored in the result array.

These fundamental operations provide the basis for advanced manipulation and analysis of Swift arrays.

Also read: Decoding Code Smells: Types, Refactoring, and Optimal Approaches

Array manipulation

As a developer, you can manipulate arrays to customize them to your needs.

Delete last N element

You may want to remove the last elements from an array. The dropLast method simplifies it:

let users : [String] = ["abc","def","xyz","pqr","xyz","xyz"]

var result = users.dropLast(2)
debugPrint(result)


OUTPUT: ArraySlice(["abc", "def", "xyz", "pqr"])

In this illustration, the dropLast method eliminates the last 2 elements from the array users and gives you a new one called result.

Spotting the minimum value 

You can locate the minimum value in an array using the min method:

let array : [Int] = [10,15,20,40,45,3]
var min = array.min() //value if has min, nil if array is empty
debugPrint(min)

OUTPUT: 3

When you apply the min method, you get the minimum value. In the case of an empty array, the operation returns nil.

Create new arrays with existing ones

You can combine existing arrays using the + operator to get new ones.


var arrayOne = [10,60,90,20]
var arrayTwo = [30, 40, 50]

var bothArray = arrayOne + arrayTwo

OUTPUT: [10,60,90,20,30,40,50]

In this illustration, two arrays (arrayOne and arrayTwo) are merged to form a new one called bothArray with the help of the + operator.

Also read: Creating Swift iOS Apps Faster and with Consistency Using Custom Xcode Templates

Filtering arrays

Filtering arrays enable you to add or remove elements selectively.

Use a boolean value to filter an array

With Swift’s filter method, you can add or eliminate elements using a boolean condition.

let numbers = [1, 2, 3, 4, 5, 6]
let evenNumbers = numbers.filter { $0 % 2 == 0 }

print(evenNumbers)

OUTPUT: [2,4,6]

In this example, the filter method helps create a new array (evenNumbers). It only contains the even-numbered elements from the original array.

These manipulations and filtering operations help you extract maximum utility from arrays in Swift programming.

Miscellaneous uses of data in an array

Sorting elements

sort() – To organize the elements of an array. Note that when you compare strings, it fetches and compares the ASCII value of the letter/string.

var rating = [95, 87, 92, 99, 84]
rating.sort()
debugPrint(rating) 
rating.sort(by: >)
debugPrint(rating)

var letters = ["a", "b", "A"]
letters.sort()
debugPrint(letters)

OUTPUT: [84,87,92,95,99]
        [99,95,92,87,84]
        [“A”,”a”,”b”]

Reversing elements

reverse() – To invert the sequence of elements in an array.

var rating = [95, 87, 92, 99, 84]
rating.reverse()
debugPrint(rating)

OUTPUT: [84,99,92,87,95]

Shuffling elements

shuffle() – To randomly change the order of elements.

var rating = [95, 87, 92, 99, 84]
rating.shuffle()
debugPrint(rating)

OUTPUT: [92,95,87,99,84]

Removing duplicates

removeDuplicates(): To eliminate the duplicate elements in an array.

let arrayWithDuplicates = ["0","1","2","3","2","3","5","6","6","7"]

func removeDuplicates(from arr: [String]) -> [String] {
    return Array(Set(arr))
}
debugPrint(self.removeDuplicates(from: arrayWithDuplicates))

OUTPUT:["1", "2", "6", "5", "3", "0", "7"]

Removing select elements

removeAll { $0 < 10 }: To eliminate elements from an array based on a given condition.

var numbers = [1,5,7,3,9,11,19,34,6,23]
numbers.removeAll { $0 < 10 }
debugPrint(numbers)

OUTPUT: [11,19,34,23]

Checking if all elements satisfy a condition

allSatisfy { $0 < 10 }: To check whether all elements of an array meet a specific condition.

var numbers = [6,2,4,9,1]
let allUnder10 = numbers.allSatisfy { $0 < 10 }
debugPrint(allUnder10)


OUTPUT:true

Picking a random element

randomElement(): To randomly select an element from an array.

var nums = [1, 2, 3, 4, 5]
let randNum = nums.randomElement()
debugPrint(randNum)

OUTPUT: 3

Replacing a regular for loop with function

forEach { debugPrint($0) }: Substitutes standard for loop with a function.

var nums = [1, 2, 3, 4, 5]
nums.forEach { debugPrint($0) }

OUTPUT:
1
2
3
4
5

Checking if the array is empty

isEmpty: To discover whether an array is empty.

var nums = [1, 2, 3, 4, 5]
debugPrint(nums.isEmpty)

OUTPUT: false

Obtaining the first element of an array

First: To extract the first element of an array.

var numbers = [9, 15, 12, 8, 17, 20, 11]
debugPrint(nums.first)


OUTPUT: 9

Mapping function over a collection

map({ $0 }): Applies a function to all elements in a collection.

let userNames: [String] = ["John","Morgan", "Rachel", "Katie", "David"]
let arrUserName = userNames.map({ $0 })
debugPrint(arrUserName)


OUTPUT: ["John", "Morgan", "Rachel", "Katie", "David"]

CompactMap to unwrap optionals and discard nil options

compactMap({ $0 }): CompactMap discard nill options after unwrapping all options.


let userNames = ["John", "Chan", nil, "Rachel", nil, "David", "Bob"]
let arrUserName = userNames.compactMap({ $0 })
debugPrint(arrUserName)


OUTPUT:["John", "Chan", "Rachel", "David", "Bob"]

FlatMap to receive a single-level collection

flatMap {$0}: Employs FlatMap to gather a collection at a single level, flattening the resulting array.

var array = [[1,2,3],[5,6,7,8]]
let flattenedArray = array.flatMap {$0}
debugPrint(flattenedArray)

OUTPUT:[1, 2, 3, 5, 6, 7, 8]

Join operation for an array

joined(): Performs a join operation on an array.


var brands = ["Dell", "HP", "Apple"]
var result = brands.joined()
debugPrint(result)


OUTPUT:"DellHPApple"

Also read: [Tutorial] Designing Impressive SwiftUI Charts Using Swift Charts

Conclusion

In this blog post, we have revealed essential tools for every Swift developer and discussed principal array operations to help you overcome common challenges and manage your tasks efficiently. Whether you want to locate an element or its index or create new arrays using the existing ones, we have manufactured an in-depth resource to assist you in your Swift programming journey.

At Aubergine Solutions, we share insights into efficient coding practices and provide premium iOS application development services to bring your projects to life.

Let’s create something exceptional. Contact us today.

author
Nikita Gondaliya
I am a iOS Developer having expertise in developing applications for mobile devices powered by Apple’s iOS operating system. I have a strong understanding of the Swift and SwiftUI framework and I am able to use its various features and build scalable and maintainable apps.