Swift Array – Replace Element

To replace an element with another value in Swift Array, get the index of the match of the required element to replace, and assign new value to the array using the subscript.

Example

In the following program, we will take an array fruits, and replace the element "cherry" with "guava".

main.swift

</>
Copy
var fruits = ["apple", "banana", "cherry", "mango"]

if let i = fruits.firstIndex(of: "cherry") {
    fruits[i] = "guava"
}

print(fruits)

Output

Swift Array - Replace Element

Conclusion

In this Swift Tutorial, we learned how to replace an element with a new value in Swift Array.