Sobes.tech
Intern

How to insert an element into an array?

sobes.tech AI

Answer from AI

Swift offers several ways to insert elements into an array:

  1. append(_:): Adds an element to the end of the array.

    var array = [1, 2, 3]
    array.append(4) // array is now [1, 2, 3, 4]
    
  2. insert(_:at:): Inserts an element at a specified index. Elements at and after this index are shifted.

    var array = [1, 3, 4]
    array.insert(2, at: 1) // array is now [1, 2, 3, 4]
    
  3. append(contentsOf:): Adds the contents of another sequence (e.g., another array) to the end of the current array.

    var array = [1, 2]
    let otherArray = [3, 4]
    array.append(contentsOf: otherArray) // array is now [1, 2, 3, 4]
    
  4. insert(contentsOf:at:): Inserts the contents of another sequence at a specified index.

    var array = [1, 4]
    let middleArray = [2, 3]
    array.insert(contentsOf: middleArray, at: 1) // array is now [1, 2, 3, 4]
    
  5. Using the +/+= operator: Concatenates arrays. The + operator creates a new array, while += modifies the existing one.

    var array = [1, 2]
    array += [3, 4] // array is now [1, 2, 3, 4]
    
    let newArray = array + [5] // newArray is [1, 2, 3, 4, 5], array remains unchanged
    

The choice of method depends on where you want to insert the element (at the end or at a specific index) and whether you are inserting a single element or multiple elements.

How to insert an element into an array? — iOS - sobes.tech