In this tutorial, we’ll be discussing about Swift Array. If you don’t know how Optional in Swift work, you can refer here before proceeding forward.
Swift Array
Array in Swift is used to store an ordered collection of values of any type (we can have more than one types in an array).
Arrays that are defined as a var
are mutable whereas the ones defined with let
are immutable. An example of each is given below:
var arrayOfStrings:[String] = ["Hello", "Playground"]
let constantArray :[String] = ["Hello", "Playground"] //Can't modify this
Let’s dive into our playground to have a deeper look at Arrays.
Swift Arrays Example
Let’s look at different operations with swift array.
Creating Array in Swift
You can either declare the type or Swift infers it as shown below.
//String array with type explicitly declared.
var arrayOfStrings:[String] = ["Hello", "Playground"]
//String array with type inferred.
var arrayOfStrings = ["Hello", "Playground"]
Swift Array Length
To get the array’s length we’ll invoke the function count
on the instance of array using the dot operator as shown below.
print(arrayOfStrings.count) //prints 2
Adding elements to an array
We can add elements to the end of an array the function append
is called on the instance of array as shown below.
arrayOfStrings.append("New Member")
arrayOfStrings.append(1)// Compilation error
print(arrayOfStrings.count) //prints 3
let mutableArray = ["I can't", "be", "modified"]
mutableArray.append("1") //Compile-time error.
Since the array is of the type String
, we’ll get an error while adding an Int
.
append
function would give a compile time error when used on an immutable array.
Append multiple elements at once
arrayOfStrings += ["Append", "Multiple", "Elements"]
arrayOfStrings += [1,2] //Compilation error. Can't add elements of a different type
Creating an empty array
To create an empty array of a particular type use the following syntax:
var someArray:[Int] = []
//or
var someArray = [Int]()
//Example 1
var intArray = [Int]()
intArray.append(3)
intArray.count //prints 1
intArray = [] //clears the contents. Back to being empty.
Creating an array with default values
Following syntax is used to create an array with repeating values and count.
var intArray: [Int] = Array(repeating: 10, count: 5)
print(intArray) //prints [10, 10, 10, 10, 10]
var boolArray: [Bool] = Array(repeating: false, count: 5) // [false, false, false, false, false]
Array()
is the default function that contains two arguments repeating
where we set the default value for each element and count
is for setting the number of elements.
Accessing and Modifying an Array
Accessing and modifying array elements using subscripts is more or less similar to other languages.
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray[0] = 2
customIntArray[customIntArray.count-1] = 11
Accessing and modifying a range of elements
To access a range of elements in an array we use the subscript syntax as shown below
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray[0...5] // returns [1, 4, 5, 7, 10, 2]
Note: The range of elements returned are inclusive of the start and end indexes ( 0 and 5 in the above case).
We can modify the values of the range of elements in place too as shown below
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray[0...5] = [0,0,0,0,0]
print(customIntArray) //prints [0, 0, 0, 0, 0, 4, 5, 34, 33, 11, 13, 17]
It’s possible to modify the range of values with a set of values having different length as shown below:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray[0...5] = [0]
print(customIntArray) //prints [0, 4, 5, 34, 33, 11, 13, 17]
In the above code we’ve replaced a range of 5 elements with a single element.
Inserting and removing at specified index
To insert an element at a specified index we use the following syntax:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray.insert(0, at: 0)
print(customIntArray) //prints [0, 1, 4, 5, 7, 10, 2, 4, 5, 34, 33, 11, 13, 17]
The insert
function inserts the value at the mentioned index and shifts the array elements to the right of it by an offset of 1.
To remove an element at a specified index we use the following syntax:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray.remove(at: 0) //returns 1
print(customIntArray)//prints [4, 5, 7, 10, 2, 4, 5, 34, 33, 11, 13, 17]
Note: The remove function returns the removed element too. You can store it if you need to as below
var removedElement = customIntArray.remove(at: 0)
To remove all elements from an array we need to invoke the method removeAll()
on the array.
To check if an array is empty or not we invoke the method isEmpty()
on the instance of array as shown below:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
if customIntArray.isEmpty {
print("array is empty")
}
else{
print("false") //this gets printed
}
Accessing the first and last elements of an array
Swift provides us with first
and last
properties to access the first and last elements of an array.
The returned value is an optional
type as shown below:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
var first = customIntArray.first
print(first) //prints Optional(1)
var last = customIntArray.last
print(last) //prints Optional(17)
if let l = last{
print(l) //prints 17
}
else{print("couldn't retrieve the last element") }
We’ve used if let
to safely get the last element’s value
To retrieve and remove the last element of an array, we call the function popLast()
which pops the last element from the array and returns it’s optional value.
if let l = customIntArray.popLast(){
print(l) //prints 17
}
else{print("couldn't retrieve the last element") }
Note: In the above example if the array is empty, the else statement would’ve been printed.
Find an element in Swift array
To check if an element is present inside an array we invoke the function contains()
on the instance of the array as shown below:
var oddArray = [1,3,5,7]
print(oddArray.contains(2)) //false
print(oddArray.contains(5)) //true
Note: The contains()
function returns as soon as the first match is found.
contains()
function has another implementation that expects a condition in the form of a function/closure as the parameter. An example is mentioned below.
var oddArray = [1,3,5,7]
print(oddArray.contains(where: {$0 > 5})) //prints true
print(oddArray.contains(where: {$0 > 10})) //prints false
//check if the array contains any even number
print(oddArray.contains(where: {$0%2 == 0})) //prints false
We’ve used a closure as the where clause in the above code snippets. If you’re unaware of closures refer here.
Reverse an array in swift
To reverse an array we call the function reverse()
on the instance of array as shown below:
var oddArray = [1,3,5,7]
oddArray.reverse()
print(oddArray) //prints [7, 5, 3, 1]
Looping over an array
A for-in
loop allows us to loop over an array without the use of indexes as shown below:
var oddArray = [1,3,5,7]
for element in oddArray {
print(element)
}
To display index value as well as element we call the enumerated()
function on the array in the for-in
loop as shown below:
var stringArray = ["Hey", "How", "You","Doing"]
for (index, value) in stringArray.enumerated() {
print("(index) : (value)") //prints index value pair
}
//prints :
0 : Hey
1 : How
2 : You
3 : Doing
To iterate over the array in reverse order inside the for-in
loop we call the function reversed()
over the array.
var oddArray = [1,3,5,7]
for number in oddArray.reversed() {
print(number)
}
//prints:
7
5
3
1
Combining and comparing two arrays
To combine two arrays you can simply add them as shown below:
let oddArray = [1,3,5,7]
let evenArray = [0,2,4,6,8]
let completeArray = evenArray + oddArray // contains [0, 2, 4, 6, 8, 1, 3, 5, 7]
To compare if two arrays are equal or not we use the function elementsEqual()
as shown below:
let oddArray = [1,3,5,7]
let oddArrayTwo = [1,3,5,7]
let evenArray = [0,2,4,6,8]
evenArray.elementsEqual(oddArray) //false
oddArray.elementsEqual(oddArrayTwo) //true
Swift Multidimensional Array
A multidimensional array is declared in the following manner.
var arrayOfArrays = [[String]]()
var aA = ["AA","AB","AC"]
var bA = ["BA","BB","BC"]
var cA = ["CA","CB","CC"]
arrayOfArrays.append(aA)
arrayOfArrays.append(bA)
arrayOfArrays.append(cA)
print(arrayOfArrays)//prints: [["AA", "AB", "AC"], ["BA", "BB", "BC"], ["CA", "CB", "CC"]]
arrayOfArrays[0].append("AD")
arrayOfArrays[1].append("BD")
arrayOfArrays[2].append("CD")
print(arrayOfArrays)//prints: [["AA", "AB", "AC", "AD"], ["BA", "BB", "BC", "BD"], ["CA", "CB", "CC", "CD"]]
This brings an end to swift array tutorial.