Insert An Element At The Beginning Of An Array In Swift
Code snippet for how to Insert An Element At The Beginning Of An Array In Swift with sample and detail explanation
Swift, a powerful and intuitive programming language for macOS, iOS, watchOS, and tvOS, provides various ways to manipulate arrays. In this article, we will focus on a practical case of array manipulation: inserting an element at the beginning of an array.
Code snippet: Inserting an element at the beginning of an array in Swift
// Declare an array
var array = ["Apple", "Banana", "Cherry"]
// Insert an element at the beginning
array.insert("Mango", at: 0)
// Print the array
print(array)
Code Explanation: Inserting an element at the beginning of an array in Swift
In Swift, an array is a pretty straightforward data type. It’s essentially a list of elements in a certain order. You can add or remove the elements from an array quite easily. Here, we will explain how the given code works to add an element at the start of an array.
-
Declaration of Array:
var array = ["Apple", "Banana", "Cherry"]
The first line of the code defines an array named “array” containing three string elements: “Apple”, “Banana”, “Cherry.”
-
Insertion of Element at the Beginning:
array.insert("Mango", at: 0)
The second line uses the ‘insert’ function of the array. The ‘insert’ function takes two arguments: the first one is the element that you want to insert, and the second one is the position where the element should be inserted. The index of an array starts from ‘0’, so to add the element at the start of the array, you need to specify the position as ‘0’. Here, it inserts “Mango” at the 0th position or the beginning of the array.
-
Print the Array:
print(array)
Finally, we print out the array to see our results. After executing the code, you should see [“Mango”, “Apple”, “Banana”, “Cherry”].
That’s it! Now you know how to insert an element at the beginning of an array in Swift. This basic operation can be useful in many situations while building apps in Swift.