
This tutorial shows multiple ways to add an element to an array in swift with examples.
- add an element to end of an array using
append
method.[1,2].append(3)
returns[1,2,3]
- Add an element at index position using insert method.
[11,12].insert(2,0)
adds an element at index=0, returns[2,11,12]
- += operator that adds element to end.
["one", "two"]+=["three"]
returns["one", "two","three"]
An array is a group of elements with the same type. Each element is accessed with an index. The first element starts with index=0, the last element ends with index=length-1.
Elements can be added to the start, middle, or end of an array.
How to add an element to an array in swift
There are multiple ways we can add an element either start, end, or index=0.
append
method
Use the append
method to add an element to the end of an array.
Syntax:
mutating func append(_ newElement: Element)
// add an element to end of an array
numbers.append("five")
To add an element or sub array to an end of an array.
// add an subarray to end of an array
numbers.append(contentsOf: ["six", "seven"])
Here is a complete example
import Foundation
var numbers = ["one", "two", "three", "four"]
print(numbers)
// add an element to end of an array
numbers.append("five")
print(numbers)
// add an subarray to end of an array
numbers.append(contentsOf: ["six", "seven"])
print(numbers)
insert
method
insert
method adds an element at index position zero.
Syntax:
mutating func insert(
_ newElement: Element,
at i: Int
)
To add an element to the index of an array.
// add an element to an array index=1
numbers.insert("five",1)
To add an element or sub array to an end of an array.
// add an subarray to array index=3
numbers.insert(contentsOf: ["six", "seven"],at:3)
Here is a complete example
import Foundation
var numbers = ["one", "two", "three", "four"]
print(numbers)
// add an element to end of an array
numbers.insert("five",at:1)
print(numbers)
// add an subarray to end of an array
numbers.insert(contentsOf: ["six", "seven"],at:3)
print(numbers)
Output:
["one", "two", "three", "four"]
["one", "five", "two", "three", "four"]
["one", "five", "two", "six", "seven", "three", "four"]
- use += operator
Another way using the +=
operator.
It adds single or multiple elements to the end of the array.
Here is an example
import Foundation
var numbers = ["one", "two", "three", "four"]
print(numbers)
// add an element to end of an array
numbers += ["five"]
print(numbers)
// add an subarray to end of an array
numbers += ["six", "seven"]
print(numbers)
Output:
["one", "two", "three", "four"]
["one", "two", "three", "four", "five"]
["one", "two", "three", "four", "five", "six", "seven"]