Collection Types in Swift

I am starting this Collection Type tutorial in the assumption that you have knowledge on Datatypes like int, string. If you want to refresh, please go through our Datatypes and String tutorial.

Lets come back to Swift Collection, it is used to store multiple values of the same type in a type. There are three types of collection in Swift 3.

  1. Arrays
  2. Set
  3. Dictionary

Arrays elements are ordered collection type, whereas Set and Dictionary are unordered collection ttypes,elements in Set and Dictionary are not ordered.

Another difference between Array and Set is, Array can have duplicated elements , but values are unique in Set.

Arrays:

As we said earlier, an array is an ordered collection type, and it can have same values in multiple index i.e duplicated values.

and declaration is Array<Element>, where Element is a type of the value that array is holding. We will see an example in next section.

Array Initialisation:

If you are from String tutorial in our last chapter, this will be easier for you to understand all the initialisation in Swift.

let myFirstArray : Array<Int> = [1,2,3,4]

in shorthand , we can initialize an array as  

let myFirstArray = [1,2,3,4]

Those two examples are constant arrays and we can not modify it since its keyword is declared as let.

Below is an example of creating an empty array and followed by its shorthand.

var mutableFirstArr = [Int]()

var mutableFirstArr = [] // shorthand empty array

Since it is declared with var, it is mutable and we can modify this array values at any time.

Accessing Arrays:

Accessing array is nothing but a getting the number of element from that array, get the value from particular index, modify the value at particular index, add or remove a value to/from an array

Let’s start with count,  let’s take our previous example back here

let myFirstArray = [1,2,3,4]

The number of elements that array stored can be read by count method.

print(myFirstArray.count) , it prints as 4, since it has 4 values such as 1,2,3,4

Empty Array:

To determine the empty state of an array, we can use count method again, if it is zero, then the array is not having any values.

Another simple method is there in Swift, isEmpty, to check the empty array. Here no need to check the count is equal to 0 or not, pretty simple right?.

if myFirstArray.isEmpty {

  print("array is empty")

}

else {

    print("array is not empty")

}

Add & Delete :

Another key factor in a programming language is to add an element of an array. append() in Swift help us to add a new value to an existing array at the end. Let’s take the same array but with var keyword, since we are going to change it by adding a value.

var mutableFirstArr = [1,2,3,4]

mutableFirstArr.append(5

Here I am appending number 5 at end of the array.

Alternatively, we can join two compatible type arrays using + operator easily.

mutableFirstArr += [6]

in the above line, I am adding an array that has single int element as 6 to an existing array.

We have knowledge now to add a value at the end, so next is to add value at the particular index.

mutableFirstArr.insert(0, at: 0)

The above example explains the insert method and takes an argument with at label that is the index position to insert the value in that array. Ok, Next thought in your mind would be deleting a value from an array. Am I right?

mutableFirstArr.remove(at: 5)

remove method that takes index position to delete the value from that position.

another short form to delete the last element of an array is removeLast().

Accessing array using Subscript:

To read or change a value from a particular position of an array, subscript syntax can be used. It is very simple to use.

mutableFirstArr[5] = 6

The above example replaces the value that is at the 5th position to a new value as 6.

Below is playground screenshot to brief our array tutorial.

Screen Shot 2017 04 15 at 10 27 54 PM

Array iteration:

An array can be iterated using for-in loops that we will see in future.

for i in mutableFirstArr{

    print(i)

}

Set:

Set in swift is more or less similar to an array. But the main difference between an array and a set is, duplicated values are not allowed in Set. And Set also performs set operations like join, intersection, union, symmetric difference.

The types that are going to be stored in Set must be hashable, in order to compute its unique value internally. If a type is not hashable, it can not be stored in Set.

Set Initialisation:

Set initialization is similar to Array, here also we have different types of initialization.

let myFirstSet : Set<Int> = [1,2,3]

let mySet = [1,2,3]

var firstSet = Set<Int>() 

Since we have explained this initialisation in Array section, assume that need not to explain again. “I am bit lazy 🙂 “

Accessing and Modifying a Set:

Set can be accessed using its methods and properties.

count property is to find out the number of items or elements in a set

print(myFirstSet.count)

Just like array, Empty set can be found using isEmpty property

if myFirstSet.isEmpty

{

    print("set is empty")

}

else {

    print("set is not empty")

}

Add or remove an item:

Insert method is useful for inserting an item in an existing set, It is similar to an array, but the difference here in insert method of a set is, it won’t ask you the index position to where it needs to be placed. Can you guess that why it is like that? yep, Set is an unordered collection type, and it places the item at any place.

var firstSet = Set<Int>()

firstSet.insert(1)

And to delete an item is also same,

firstSet.remove(1)

Set iteration:

Set also can be traversed through using for-in loops.

for i in firstSet{

    print(i)

}

Playground screenshot for giving a brief about Set.
Screen Shot 2017 04 15 at 11 15 24 PM

I will write detail tutorial for dictionaries in next chapter. Please share this tutorial if you feel that I have given at least some basic knowledge,  across your friends in social media and put your words in comment section to improve my skills

Leave a Reply

Your email address will not be published. Required fields are marked *