Add an element to an array in Swift


In this article, you will learn how to add an element to an array in Swift.

Before you begin to learn element insertion into an array, you will need to understand the type of array.

Array Syntax

// Declare an immutable array
let arrayName: [valuetype] = [array element 1, array element 1, ...array element n]
// Declare a mutable array
var arrayName: [valuetype] = [array element 1, array element 1, ...array element n]

In Swift, we can declare an array with let for immutable and var for a mutable array. For an immutable array, we have to provide the array elements at the time of initialization.

How to Append an Element Into an Array?

Now, if you want to append an element to an array, we have to make it mutable using the var keyword. Let's see how to append an element.

Syntax

To add an element to an array in Swift, you can use the append method of the Array type. This method adds a new element to the end of the array.

numbers.append(n)

Basically, you can pass the element to append in the given array.

Algorithm

  • Step 1 − Declare a mutable array

  • Step 2 − Call append() method to append an element

  • Step 3 − Print the output

Example

For example, if you have an array of integers called numbers and you want to add the number 25 to it, you can do it like this −

var numbers: [Int] = [10, 20, 4, 56, 2, 67, 78]
print("Numbers before: \(numbers)")
numbers.append(25)
print("Numbers after: \(numbers)")

Output

Numbers before: [10, 20, 4, 56, 2, 67, 78]
Numbers after: [10, 20, 4, 56, 2, 67, 78, 25]

How to Add Multiple Elements at Once?

Syntax

Yes, you can add multiple elements at a time like this −

numbers.append(contentsOf: [Array Elements])

Basically, you can pass an array to append all the elements into another array that is already mutable.

Algorithm

  • Step 1 − Declare a mutable array

  • Step 2 − Call number.append() function to append multiple elements

  • Step 3 − Print the output

Example

var numbers: [Int] = [10, 20, 4, 56, 2, 67, 78]
print("Numbers before: \(numbers)")
numbers.append(contentsOf: [40, 45, 50])
print("Numbers after: \(numbers)")

Output

Numbers before: [10, 20, 4, 56, 2, 67, 78]
Numbers after: [10, 20, 4, 56, 2, 67, 78, 40, 45, 50]

You can use the += operator to append elements like the following −

numbers += [40, 45, 50]

Remember that the append() method will add elements at the end of the array.

How to Insert an Element at a Specific Index in an Array?

Syntax

numbers.insert(<Element>, at: <Index>)

In the insert() method, you have to pass an element and the index on which you want to insert that element.

Algorithm

  • Step 1 − Declare a mutable array

  • Step 2 − Call insert() method with element and index

  • Step 3 − Print the output

Example 1

If you want to insert an element at a specific index in the array, you can use the insert(_:at:) method. For example −

var numbers: [Int] = [10, 20, 4, 56, 2, 67, 78]
print("Numbers before: \(numbers)")
numbers.insert(15, at: 1)
print("Numbers after: \(numbers)")

Output

Numbers before: [10, 20, 4, 56, 2, 67, 78]
Numbers after: [10, 15, 20, 4, 56, 2, 67, 78]

This will insert the number 15 at index 1 in the numbers array, shifting the existing elements to the right.

Example 2

Note that you cannot insert an element into an array at an index that is outside the bounds of the array. The code will break with an exception like below −

var numbers: [Int] = [10, 20, 4, 56, 2, 67, 78]
numbers.insert(15, at: 10)

Output

Fatal error: Array index is out of range
Current stack trace:
0    libswiftCore.so                    0x00007f27c596a2e0 swift_reportError + 50
1    libswiftCore.so                    0x00007f27c59def40 _swift_stdlib_reportFatalErrorInFile + 112
2    libswiftCore.so                    0x00007f27c56c9026  + 1425446
3    libswiftCore.so                    0x00007f27c56c8c4f  + 1424463
4    libswiftCore.so                    0x00007f27c56c89ec  + 1423852
5    libswiftCore.so                    0x00007f27c56c8500 _assertionFailure(_:_:file:line:flags:) + 441
6    libswiftCore.so                    0x00007f27c56b4461  + 1340513
8    swift-frontend                     0x000000000058765a  + 1603162
9    swift-frontend                     0x000000000054c778  + 1361784
10   swift-frontend                     0x000000000051c4ca  + 1164490
11   swift-frontend                     0x000000000051bb7c  + 1162108
12   swift-frontend                     0x0000000000510710  + 1115920
13   swift-frontend                     0x000000000049be53  + 638547
14   libc.so.6                          0x00007f27c721ab10 __libc_start_main + 231
15   swift-frontend                     0x000000000049b96a  + 637290
Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace.
Stack dump:
0.	Program arguments: /usr/bin/swift-frontend -frontend -interpret main.swift -disable-objc-interop -module-name main 
1.	Swift version 5.4.2 (swift-5.4.2-RELEASE)
2.	While running user code "main.swift"
/usr/bin/swift-frontend[0x5806484]
/usr/bin/swift-frontend[0x5803f1e]
/usr/bin/swift-frontend[0x580666c]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f27c8995980]
/usr/lib/swift/linux/libswiftCore.so(+0x15c02a)[0x7f27c56c902a]
/usr/lib/swift/linux/libswiftCore.so(+0x15bc4f)[0x7f27c56c8c4f]
/usr/lib/swift/linux/libswiftCore.so(+0x15b9ec)[0x7f27c56c89ec]
/usr/lib/swift/linux/libswiftCore.so($ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtF+0x1b9)[0x7f27c56c86b9]
/usr/lib/swift/linux/libswiftCore.so(+0x147461)[0x7f27c56b4461]
[0x7f27c8d3a0fc]
/usr/bin/swift-frontend[0x58765a]
/usr/bin/swift-frontend[0x54c778]
/usr/bin/swift-frontend[0x51c4ca]
/usr/bin/swift-frontend[0x51bb7c]
/usr/bin/swift-frontend[0x510710]
/usr/bin/swift-frontend[0x49be53]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0x7f27c721abf7]
/usr/bin/swift-frontend[0x49b96a]
/usr/bin/timeout: the monitored command dumped core
Illegal instruction

This error clearly indicates that the element cannot be inserted at the given index because it is out of range.

Conclusion

Swift provides two different methods to modify the array. Both methods are used in different situations. While you insert an element into an array, you have to take care of the index bound.

Updated on: 03-Jan-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements