Intern
How to insert an element into an array?
sobes.tech AI
Answer from AI
In Swift, methods append, insert(at:), or operators += are used to insert elements into an array.
-
append(_:): Adds a single element to the end of the array.var array = [1, 2, 3] array.append(4) // [1, 2, 3, 4] -
append(contentsOf:): Adds the contents of another sequence (e.g., another array) to the end of the current array.var array = [1, 2, 3] let newElements = [4, 5] array.append(contentsOf: newElements) // [1, 2, 3, 4, 5] -
insert(_:at:): Inserts a single element at the specified index. Elements at and after this index are shifted to the right.var array = [1, 2, 3] array.insert(99, at: 1) // [1, 99, 2, 3] -
insert(contentsOf:at:): Inserts the contents of another sequence at the specified index.var array = [1, 2, 3] let newElements = [99, 88] array.insert(contentsOf: newElements, at: 1) // [1, 99, 88, 2, 3] -
Operator
+=: Adds either a single element (if in square brackets) or elements of another sequence to the end of the array.var array = [1, 2, 3] array += [4] // [1, 2, 3, 4] array += [5, 6] // [1, 2, 3, 4, 5, 6]