insert an element into an array at a specific index in swift

To insert an element into an array at a specific index in Swift, you can use the insert(_:at:) method. Here's an example:

main.swift
var array = ["apple", "banana", "orange"]
let index = 1 // the index at which to insert the new element
let newElement = "pear"

array.insert(newElement, at: index)
print(array) // Output: ["apple", "pear", "banana", "orange"]
227 chars
7 lines

In this example, newElement is inserted at index 1, pushing the existing element at index 1 and all subsequent elements to the right. The resulting array is ["apple", "pear", "banana", "orange"].

Note that the insert(_:at:) method modifies the original array rather than returning a new array. If you need to create a new array with the inserted element, you can use the + operator or the append() method instead.

gistlibby LogSnag