Learning Swift – Collections [Arrays]

learning swift collections arrays

Hello Friends,

A very Happy New Year to all of you.

Sorry for such a huge delay in publishing this post.

My new year resolution is to keep up at least one post every week starting today.

In this post, we delve into collections.

A collection can be defined as an object containing multiple elements.

Swift has three collection types namely Array, Set and Dictionary.

Array

An Array is an ordered list of elements of same data type. An example: Square of integers between 1 and 10.

In swift, the array can be initialized in three ways:

//Method 1
var oddNumber = Array<Int>()
oddNumber = [3, 5, 7]

In the first method, Array specifies the type of object being initialized and Int specifies the type of items stored in the array.

Presently the array oddNumber is empty. Therefore we assign some values of Integer type to it.

//Method 2
var price = [Double]()

price.append(14.6)
price.append(56.3)
price.append(14.6)

print(price)

In the second method, the square brackets ensure compiler knows the price is an array and double defines the type of the items in that array.

append() method is used to add items to an array. This method always adds elements to the end of the array.

//Method 3
//var house : [String] =["Gryffindor", "Hufflepuff"]
var house = ["Gryffindor", "Hufflepuff"]

Here we use the array literal to initialize the array. [String] is used to indicate an array of string.

Array Operations

//Operations on array

//append
house.append("Ravenclaw")

//insert
house.insert("Slytherin", at: 1)

//remove
house.remove(at: 1)

print(house)

//count
print(house.count)

//retrieve
print(house[2])

Append, Insert, Remove, Count, and Retrieve are the operations that can be performed on arrays.

Append is used to add items at the end of an array. Here we are adding “Ravenclaw” to the array “house”. Ravenclaw is added to the end of the array.

Insert is used to add items at a desired position in the array.

insert(newElement: Element, at: Int)

Here newElement is the element we want to add in the array. And after at: we specify the index at which element will be added.

In our example, we are adding “Slytherin” and index 1. Array index start from 0, so Slytherin gets added after Gryffindor which is at 0. Rest elements are shifted one place down.

Remove is used to delete items in the array.

“remove(at: Int)”

Here we just need to specify the index of the element we want to delete.

In our example we are deleting “Slytherin” which is at 1.

Count returns the total number of items in the array.

We can retrieve any element of the array through its index. Here we want to access Ravenclaw. So we use the index of Ravenclaw.

You can find the code for this project here

We will study sets and dictionaries in the following posts.

Happy New Year once again.