Replace an array element with another element in Swift
In this tutorial, we will learn how to replace an array element with another.
For this we need to:
- Find the index of the element you want to replace.
- Replace the element at this index.
So, let’s proceed with the task to replace an array element with another,
First of all, create an array consisting of elements of your choice (as per requirements).
var city=["Bhopal","Pune","Bangalore","Chennai"]
This will create an array consisting of above-mentioned elements
Method 1: If you know the index number of the element
For example, if you need to replace the element at the 3rd index-
city[3]="Mumbai" print(city)
Output ["Bhopal", "Pune", "Bangalore", "Mumbai"]
Method 2: Find the index
If you are not sure about its index, but you are sure about the element. At this point, we would find the index of the element and then we will replace its value-
var city=["Bhopal","Pune","Bangalore","Chennai"] if let i = city.firstIndex(of: "Pune") { city[i] = "Nagpur" } print(city)
Output: ["Bhopal", "Nagpur", "Bangalore", "Chennai"]
We have completed the task.
Leave a Reply