Swift Array
Array in Swift is used to store an ordered collection of values of any type (we can have more than one type 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:
import Foundation 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 and look at different operations with the swift array.
Creating an Array
In Swift, You can either declare the type or Swift infers it as shown below.
import Foundation var arrayOfStrings:[String] = ["Hello", "Playground"] //String array with type explicitly declared. var arrayOfStrings = ["Hello", "Playground"] //String array with type inferred.
Swift Array Length
To get the array’s length we’ll invoke the function count on the instance of an array using the dot operator as shown below.
import Foundation let arrayOfStrings:[String] = ["Hello", "Playground"] 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 an array as shown below.
import Foundation var arrayOfStrings:[String] = ["Hello", "Playground"] arrayOfStrings.append("New Member") print(arrayOfStrings.count) //prints 3
append function would give a compile-time error when used on an immutable array
import Foundation let mutableArray = ["I can't", "be", "modified"] mutableArray.append("1") //Compile-time error. //Cannot use mutating member on immutable value: 'mutableArray' is a 'let' constant
Since the array is of the type String, we’ll get an error while adding an Int.
import Foundation var arrayOfStrings:[String] = ["Hello", "Playground"] arrayOfStrings.append(1) //Cannot convert value of type 'Int' to expected argument type 'String'
Append multiple elements at once
import Foundation var arrayOfStrings:[String] = ["Hello", "Playground"] arrayOfStrings += ["Append", "Multiple", "Elements"] print(arrayOfStrings.count) //prints 5
Creating an empty array
[quote font=”georgia”]var someArray:[Int] = [][/quote]
[quote font=”georgia”]var someArray = [Int]()[/quote]
import Foundation var intArray = [Int]() intArray.append(3) print(intArray.count) //prints 1 intArray = [] //clears the contents. Back to being empty. print(intArray.count) //prints 0
Creating an array with default values
Following syntax is used to create an array with repeating values and count.
import Foundation var intArray: [Int] = Array(repeating: 10, count: 5) print(intArray) //prints [10, 10, 10, 10, 10] var boolArray: [Bool] = Array(repeating: false, count: 5) // prints [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.
import Foundation var customIntArray = [10,2,30,40,5] customIntArray[1] = 20 customIntArray[customIntArray.count-1] = 50 print(customIntArray) //prints [10, 20, 30, 40, 50]
Accessing and modifying a range of elements
To access a range of elements in an array we use the subscript syntax as shown below
import Foundation var customIntArray = [10,20,30,40,50,60,70] customIntArray[0...4] //[10, 20, 30, 40]
[quote font=”georgia”]Note: The range of elements returned is inclusive of the start and end indexes ( 0 and 4 in the above case).[/quote]
We can modify the values of the range of elements in place too as shown below
import Foundation var customIntArray = [10,20,30,40,50,60,70] customIntArray[0..<5] = [0,0,0,0,0] print(customIntArray) //prints [0, 0, 0, 0, 0, 60, 70]
It’s possible to modify the range of values with a set of values having a different length as shown below:
import Foundation var customIntArray = [10, 20, 30, 40, 50, 60, 70, 80, 90] customIntArray[0...5] = [0] print(customIntArray) //prints [0, 70, 80, 90]
[quote font=”georgia”]In the above code, we’ve replaced a range of 5 elements with a single element.[/quote]
Inserting and removing at a specified index
To insert an element at a specified index we use the following syntax
import Foundation var customIntArray = [10,20,30,40,50] customIntArray.insert(60, at: 0) print(customIntArray) //prints [60, 10, 20, 30, 40, 50]
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:
import Foundation var customIntArray = [10, 20, 30, 40, 50] customIntArray.remove(at: 0) //returns 10 print(customIntArray)//prints [20, 30, 40, 50]
[quote font=”georgia”]Note: The remove function returns the removed element too. You can store it if you need to as below[/quote]
To remove all elements from an array we need to invoke the method removeAll() on the array.
import Foundation var customIntArray = [10, 20, 30, 40, 50] print(customIntArray.count) //prints 5 customIntArray.removeAll() print(customIntArray.count) //prints 0
To check if an array is empty or not we invoke the method isEmpty() on the instance of an array as shown below:
import Foundation var customIntArray = [10, 20, 30, 40, 50] 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:
import Foundation var customIntArray = [10, 20, 30, 40,50] var first = customIntArray.first print(first) //prints Optional(10) var last = customIntArray.last print(last) //prints Optional(50)
first and last returns optional values so we have to use if let to safely get the last element’s value
import Foundation var customIntArray = [10, 20, 30, 40,50] var first = customIntArray.first if let firstValue = first { print(firstValue) //prints 10 } else { print("couldn't retrieve the first element") } var last = customIntArray.last if let lastValue = last { print(lastValue) //prints 50 } else { print("couldn't retrieve the last element") }
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 its optional value.
import Foundation var customIntArray = [10, 20, 30, 40,50] if let last = customIntArray.popLast(){ print(last) //prints 50 } else { print("couldn't retrieve the last element") }
[quote font=”georgia”]Note: In the above example if the array is empty, the else statement would’ve been printed.[/quote]
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:
import Foundation var oddArray = [10,30,50,70] print(oddArray.contains(20)) //false print(oddArray.contains(50)) //true
[quote font=”georgia”]Note: The contains() function returns as soon as the first match is found.[/quote]
contains() function has another implementation that expects a condition in the form of a function/closure as the parameter. An example is mentioned below.
import Foundation var oddArray = [10,30,50,70] print(oddArray.contains(where: { $0 > 50 })) //prints true print(oddArray.contains(where: { $0 > 100 })) //prints false //check if the array contains any odd number print(oddArray.contains(where: { $0%2 == 1})) //prints false
We’ve used a closure as the where clause in the above code snippets. If you’re unaware of closures refer to Swift Closure.
Reverse an array in swift
To reverse an array we call the function reverse() on the instance of an array as shown below:
import Foundation var evenArray = [10,30,50,70] evenArray.reverse() print(evenArray) //prints [70, 50, 30, 10]
Looping over an array
A for-in loop allows us to loop over an array without the use of indexes as shown below:
import Foundation var evenArray = [10,30,50,70] for element in evenArray { print(element) }
To display index value as well as an element we call the enumerated() function on the array in the for-in loop as shown below:
import Foundation var evenArray = [10,30,50,70] for (index, value) in evenArray.enumerated() { print("\(index) : \(value)") } //Prints //0 : 10 //1 : 30 //2 : 50 //3 : 70
To iterate over the array in reverse order inside the for-in loop we call the function reversed()over the array.
import Foundation var evenArray = [10,30,50,70] for element in evenArray.reversed() { print(element) }
Combining and comparing two arrays
To combine two arrays you can simply add them as shown below:
import Foundation let oddArray = [1,3,5,7] let evenArray = [2,4,6,8] let completeArray = evenArray + oddArray print(completeArray) //contains [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:
import Foundation 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.
import Foundation 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"]]