Introduction to Swift Array - swift 3/swift 4/swift 5

Swift Collection tutorial : Array :

array,set and dictionary : these three collection types are available in swift. In this tutorial, we will learn about array in details. Notes :

  1. Array stores values of same types
  2. All values are in a ordered list
  3. Same value can appear multiple times
  4. If you create an array and assign it to a variable, it will be mutable. If you assign it to a constant, it will be immutable.

Creating an Array :

We can create an array with type declaration or without type declaration :

var dayArray:[String] = ["Monday","Tuesday"]
var dayArray2 = ["Monday","Tuesday"]

For the second array, since all values are of the string type, swift will infer that [String] is the correct type for this variable.

Creating an empty Array :

We can create an empty array like below in swift :

var myArr:[String] = []
var myArr2 = [String]()

Both will create an empty array .

Creating an Array with a default value with count in Swift :

We can create an array of certain size with all of its value as same :

import UIKit

var myArr:[String] = Array(repeating: "A", count: 5)

print (myArr)

It will print :

["A", "A", "A", "A", "A"]

Adding two Array :

If two arrays are added, one new array is created in swift .

import UIKit

var firstArr:[String] = Array(repeating: "A", count: 5)
var secondArr:[String] = Array(repeating: "B", count: 5)
var thirdArr = firstArr + secondArr

print (thirdArr)

Output :

["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]

Accessing and Modifying a Swift Array :

Add elements, Check if empty and print count :

We can add an element to an array using append() method. Assignment operator (+=) can also be used to append one or more elements. Use Boolean isEmpty property to check if an array is empty or not. To get the no of elements, check its count property.

The below example will clarify your doubts :

import UIKit

var myArray:[String] = []

if(myArray.isEmpty){
    print ("array is empty ")
}else{
    print ("array is not empty ")
}

print ("adding element to the array ..")

myArray.append("Monday")
print ("size of the array \(myArray.count)")

print ("adding one more element ")
myArray += ["Tuesday"]
print ("size of the array \(myArray.count)")

print ("adding two more elements ")
myArray += ["Wednesday","Thrusday"]

print ("final size of the array \(myArray.count)")
print ("final array : \(myArray)")

Output :

array is empty
adding element to the array ..
size of the array 1
adding one more element
size of the array 2
adding two more elements
final size of the array 4
final array : ["Monday", "Tuesday", "Wednesday", "Thrusday"]

Accessing, changing and deleting elements of an Array in swift :

Access an element : Using the index number, we can access elements of an array. e.g. :

import UIKit

var myArray:[String] = []

myArray = [ "Monday","Tuesday","Wednesday"]

print (myArray[0]) //print Monday

How to Change an element in an Array :

To change an element, we can use ’=’ sign :

import UIKit

var myArray:[String] = []

myArray = [ "Monday","Tuesday","Wednesday"]

print ("array before changing '\(myArray)'")


myArray[0] = "Sunday"

print ("array after changing '\(myArray)")

Output :

array before changing '["Monday", "Tuesday", "Wednesday"]'
array after changing '["Sunday", "Tuesday", "Wednesday"]

How to Replace elements in a range in an array :

We can replace elements of a range with different elements like below :

import UIKit

var myArray:[String] = []

myArray = [ "Monday","Tuesday","Wednesday","Thrusday","Friday"]

print ("array before changing '\(myArray)'")


myArray[0...3] = ["Sunday","Monday"]

print ("array after changing '\(myArray)")

It will replace all elements from position 0 to 3 with [“Sunday”,“Monday”]. So, the output will be :

array before changing '["Monday", "Tuesday", "Wednesday", "Thrusday", "Friday"]'
array after changing '["Sunday", "Monday", "Friday"]

Insert , remove, removefirst and removelast methods in array :

import UIKit

var myArray:[String] = []

myArray = [ "Monday","Tuesday","Wednesday","Thrusday","Friday"]

print ("array before changing : '\(myArray)'")


myArray.insert("Sunday", at: 0)
print ("array after new element inserted : '\(myArray)")


myArray.remove(at: 2)
print ("array after element at position 2 is deleted : '\(myArray)")

myArray.removeFirst()
print ("array after first element removed : '\(myArray)")

myArray.removeLast()
print ("array after last element removed : '\(myArray)")

Output :

array before changing : '["Monday", "Tuesday", "Wednesday", "Thrusday", "Friday"]'
array after new element inserted : '["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday"]
array after element at position 2 is deleted : '["Sunday", "Monday", "Wednesday", "Thrusday", "Friday"]
array after first element removed : '["Monday", "Wednesday", "Thrusday", "Friday"]
array after last element removed : '["Monday", "Wednesday", "Thrusday"]

Inserting an element increases the array size.

Check first and last element of an array in Swift :

We can use .first and .last to get the first and last elements of an array . It returns values as Optional type :

import UIKit

var myArray:[String] = []

myArray = [ "Monday","Tuesday","Wednesday","Thrusday","Friday"]

print ("first element of the array is '\(myArray.first)")

print ("last element of the array is '\( myArray.last)")

Output :

first element of the array is 'Optional("Monday")
last element of the array is 'Optional("Friday")

Check if an element exist in an array :

Use contains to check if an element exist in an array or not :

import UIKit

var myArray:[String] = []

myArray = [ "Monday","Tuesday","Wednesday","Thrusday","Friday"]

print ("\(myArray.contains("Monday"))")

Output :

true

Reverse and compare two swift array :

Reverse an array :

import UIKit

var myArray:[String] = []

myArray = [ "Monday","Tuesday","Wednesday","Thrusday","Friday"]
print ("array before rotation \(myArray)")

myArray.reverse()
print ("array after rotation \(myArray)")

Output :

array before rotation ["Monday", "Tuesday", "Wednesday", "Thrusday", "Friday"]
array after rotation ["Friday", "Thrusday", "Wednesday", "Tuesday", "Monday"]

Compare two array as below :

import UIKit

var myArray = [ "Monday","Tuesday","Wednesday","Thrusday","Friday"]
var myArray2 = [ "Monday","Tuesday","Wednesday","Thrusday","Friday"]

print ("Equality check \(myArray.elementsEqual(myArray2))")

It will print true

Iterate over a swift array :

To iterate over a swift array, we can use for-in loop or enumerated() :

import UIKit

var myArray = [ "Monday","Tuesday","Wednesday","Thrusday","Friday"]

for item in myArray {
    print (item)
}

print ("With index :")

for (index,value) in myArray.enumerated(){
    print("\(index) : \(value)")
}

Output :

Monday
Tuesday
Wednesday
Thrusday
Friday
With index :
0 : Monday
1 : Tuesday
2 : Wednesday
3 : Thrusday
4 : Friday

That’s all for ’array in swift’. If you have any queries, please drop one comment below.