Sobes.tech
Junior — Middle

How can you implement adding a new element to an array in your program?

sobes.tech AI

Answer from AI

In Swift, to add a new element to an array, you use the append method or the += operator.

Example with append:

var numbers = [1, 2, 3]
numbers.append(4) // now numbers = [1, 2, 3, 4]

Example with the += operator:

var numbers = [1, 2, 3]
numbers += [4] // now numbers = [1, 2, 3, 4]

If the array is declared as let, it cannot be modified, so to add an element, the array must be declared with var.