Set, Array and Dictionary what’s the differences?

Swift provides three collection types for storing collections of values

Here we will try to show the differences between them so you can easily decide which one to use in every situation.

Array:

Array is ordered collection so you can access any element inside it using its index.

Arrays can contain duplicates.

Arrays store any kind of elements from strings and integers  to classes

Array stores elements of the same type.

Usually we use arrays when ordering is needed or to store non hashable types that are not supported by Set.

Also we might use array if object can exit more than one time in collection.

Code examples in Swift 3:

This is how you create array of Strings

var shoppingList : [String] = ["Milk", "Eggs", "Cheese"]

And this is how you access element by its index

let item = shoppingList[2]

Set:

Sets Are unordered collection

Set can not contain duplicates

Sets can store only Hashable types or custom types that conforms to Hashable protocol

Set stores elements of the same type

We use Set instead of array when order is not important, and we need to ensure that each element appears only one time in collection.

Also we might use Sets when we want to test efficiently for membership.

Code examples in Swift 3:

Creating a Set of Strings

var shoppingList: Set = ["Milk", "Eggs", "Cheese"]

Checking for particular object

if shoppingList.contains("Eggs") {
    print("we need to buy eggs")
}
else{
    print("we don't need to buy eggs")
}

Dictionary:

Dictionary is an unordered collection.

Dictionaries can not contain duplicates.

Dictionaries store associations between keys of the same type with values of the same type.

Keys act as identifier and you access a value in dictionary by using its identifier unlike arrays where you can access an object using its index.

We use dictionary when we need quick access to elements in a collection using its identifier.

Code examples in Swift 3

This how we create Dictionary of Strings

var countryList: Dictionary = ["usa" : "United States", "uk" : "United Kingdom", "uae" : "Emirates"]

Checking for object using its key and reading its value

if let country = countryList["uk"] {
    print(country)
}
else {
    print("no such thing")
}

Finally its always better to take a few moments reading the class documentation from Apple before using it.

Leave a Reply

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