Remove Item From Array In Swift
Code snippet for how to Remove Item From Array In Swift with sample and detail explanation
Working with arrays is a common task for many programmers, regardless of the programming language they use. In this article, we will discuss a common operation in Swift: how to remove an item from an array.
Code snippet for removing an item from an array in Swift
Here is the Swift code snippet for removing an item from an array:
var sampleArray = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
if let index = sampleArray.firstIndex(of: "Cherry") {
sampleArray.remove(at: index)
}
print(sampleArray) // Will output: ["Apple", "Banana", "Date", "Elderberry"]
Code Explanation for removing an item from an array in Swift
The code above demonstrates how to remove an item from an array using the firstIndex(of:)
method and the remove(at:)
method provided by Swift.
-
We start by creating an array of strings called
sampleArray
which contains the items: “Apple”, “Banana”, “Cherry”, “Date”, “Elderberry”. -
We next use the
firstIndex(of:)
function to find the index of the item “Cherry”.firstIndex(of:)
is a Swift array method that returns the first index where the specified value appears in the array. If the specified item is not found in the array,firstIndex(of:)
will returnnil
. -
In order to handle the case where
firstIndex(of:)
may returnnil
, we use an optional binding (if let
) to assign the index of “Cherry” to a constant namedindex
. IffirstIndex(of: "Cherry")
returnsnil
, theif let
block will not execute. -
If
index
is successfully assigned a value (which means “Cherry” was found in the array), we then callremove(at:)
onsampleArray
to remove the item at that index. -
Finally, we print the
sampleArray
to verify that “Cherry” has been removed. The output will be: [“Apple”, “Banana”, “Date”, “Elderberry”].
And that’s how you can remove an item from an array in Swift.