OneBite.Dev - Coding blog in a bite size

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.

  1. We start by creating an array of strings called sampleArray which contains the items: “Apple”, “Banana”, “Cherry”, “Date”, “Elderberry”.

  2. 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 return nil.

  3. In order to handle the case where firstIndex(of:) may return nil, we use an optional binding (if let) to assign the index of “Cherry” to a constant named index. If firstIndex(of: "Cherry") returns nil, the if let block will not execute.

  4. If index is successfully assigned a value (which means “Cherry” was found in the array), we then call remove(at:) on sampleArray to remove the item at that index.

  5. 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.

swift