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.swift227 chars7 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