OneBite.Dev - Coding blog in a bite size

Extract A Sub-Array From An Array In Swift

Code snippet for how to Extract A Sub-Array From An Array In Swift with sample and detail explanation

Working with arrays is a common task in programming and in Swift, extracting a sub-array from an array is a straightforward task. In this article, we will demonstrate how to perform this operation with a simple use case scenario.

Code snippet for Extracting a Sub-Array from an Array in Swift

let array = [10, 20, 30, 40, 50, 60, 70, 80, 90]
let subArray = Array(array[2...5])
print(subArray)

In this code snippet, we have a parent array with the elements 10 to 90. From this parent array, we are extracting a sub-array which, includes elements from the 2nd index to the 5th index.

Code Explanation for Extracting a Sub-Array from an Array in Swift

In Swift, we can create a sub-array from an array by specifying a range of indices. Let’s break the code down:

  1. let array = [10, 20, 30, 40, 50, 60, 70, 80, 90]: Here we are declaring and initializing an array of integers which our sub-array will later be extracted from.

  2. let subArray = Array(array[2...5]): This is where the extraction of the sub-array happens. We use the slicing feature on our parent array array[2...5] - this is a range that tells Swift to take elements from the 2nd to the 5th index. Keep in mind that Swift arrays use 0-based indexing, therefore 2...5 corresponds to the 3rd, 4th, 5th, and 6th elements in our array. We then pass that slice to the Array initializer Array(), which in turn creates a new array from those elements.

  3. print(subArray): Lastly, we print our sub-array to see the outcome of the extraction.

After running the script, the console should display the sub-array [30, 40, 50, 60] which are the elements at indices from 2 to 5 in our parent array.

In conclusion, Swift provides a simple and quick way to extract a sub-array from an array, increasing the flexibility and ease of manipulating data stored in arrays.

swift