Introduction To Swift: Basics (Part 2)

Introduction To Swift: Basics (Part 2)

Exploring collection types and their operations in Swift.

Collection Types in Swift

Swift has 3 collection types named Arrays, Sets, and Dictionaries which we can use to store the collection of values. In the swift collection, we can also provide types for values and keys which makes us clear about what type of value we can insert and what type of value we will get. When we define the collection with var that means as a variable we can make changes to the collection i.e. collection is a mutable and if we define with let that means as constant we can not make changes to the collection i.e. collection is immutable.

Array

An array stores values of the same type. Arrays in Swift also start with zero indexes as in any other programming language. The syntax to define array is swift is as follows:

Array<Element> or [Element]

where Element is a type of values stored in the array. Let's see how we can define an array named ids of Int type. First, we will define variable ids and then will define its type as Array<Int> (means Array of Int) then next we can assign value to it.

var ids: Array<Int>  = [1, 2, 3, 4, 5]

An array of string type

var superHeros: [String] = ["IronMan", "Captain America", "SpiderMan", "Hulk", "BatMan", "SuperMan", "Flash"]

count

We can check the length of the array using the count

var superHeros: [String] = ["IronMan", "Captain America", "SpiderMan", "Hulk", "BatMan", "SuperMan", "Flash"]
print(MCUHeros.count)

Accessing elements from an array

We can access the element from an array by passing the index of the element we want to get within square brackets immediately after the name of the array.

superHeros[0]

Here we are passing index 0 which means we will get the first element of an array i.e. IronMan.

Modifying an array

We can also modify values in the array by using an index like this

superHeros[3] = "Thor"

Here we are assigning a new value Thor to the element at index 3 in superHeros array. Also, we can use the insert method which takes the first param as a new value and the second as the index of the position where we want to insert a new element

superHeros.insert("AntMan", at: 2)

To add a new element at the end of the array we can use the append method

superHeros.append("Dr. Strange")

To sort an array we also have a method called sort.

superHeros.sort()

the sort() performs sorting in ascending order but we can also do sorting in descending order like this

superHeros.sort(by: >)

by: > means in descending order and by: < means in ascending order

sort() updates the same array but if we want a new copy with sort applied without affecting the original array we can use the sorted method instead

superHeros.sorted()

In the same way, we have reverse() and reversed() to reverse an array and create a reverse array copy.

Dictionary

A dictionary stores the relation between keys (all keys of the same type) and values (all values of the same type ) in a collection. Unlike items in an array, items in a dictionary don’t have a specified order. Each value has a unique key which we use to get the value from the dictionary.

Syntax :

Dictionary<Key, Value>
// or
[Key: Value]

where Key is the type of value that will be used as a dictionary key, and Value is the type of value that the dictionary will store for those keys.

In the below example, we defined musicGenreClassification dictionary in which keys are the music genre and values are names of songs and both keys and values are types of strings.

var musicGenreClassification: [String: String] = [
    "Country": "I Walk the Line",
    "Electronic": "Clarity"
]

Creating an empty dictionary

var playlist: [Int: String] = [:]

Here we defined an empty dictionary playlist that has keys of type Int and values of type String. In this, dictionary we can store songID and songName as key-value pairs.

Accessing the dictionary

We can use a key to access values from the dictionary like this:

musicGenreClassification["Electronic"]

Here we are accessing song for key Electronic.

Extras

If you print the value of musicGenreClassification["Electronic"] you will get something like this: "Optional("Clarity")\n" instead of just string "Clarity". But why? 🤷🏻‍♂️

This is because they are chances that sometimes the key we passed to access value from the dictionary is not present in such case it will be nil. So here Optional() means it will either return a value if exist or nil if it does not exist.

Then how can we get actual value? 🤔

  • Forced unwrapping: Forced unwrapping means basically I know the actual value is present it's not nil so just return the value. We can achieve forced unwrapping by just adding (!) at the end like this:
musicGenreClassification["Electronic"]!
//output: Clarity

by just adding ! we got the actual value. But if in some cases the value is not present then doing so will crash the program with an error Fatal error: Unexpectedly found nil while unwrapping an Optional value

  • Conditional unwrapping: In conditional unwrapping, we use the if statement to check the optional value is not nil, then assign the unwrapped value to a new constant and use that constant variable for further operations.

if let songName = musicGenreClassification["Electronic"] {
    print(songName)
}
//output: Clarity

By using the above code it will execute the print only if a value exists for the provided key. In this way, we can prevent the program from crashing.

Modifying the dictionary

To add a new entry in a dictionary use a new key of the appropriate type as an index and assign a new value of the correct type.

musicGenreClassification["Jazz"] = "So What"

We can also use the following syntax to change the value associated with a particular key.

Dictionary[key] = "New Value"

Also, there is a method called updateValue which updates the value stored in the dictionary for the given key or adds a new key-value pair if the key does not exist.

Dictionary.updateValue("New Value", forKey: "Key")

To remove a key from the dictionary, we can set the key to nil or use a method called removeValue.

// Method One
Dictionary["Key"] = nil

// Method Two
Dictionary.removeValue(forKey: "Key")

Sets

A set stores distinct values of the same type in a collection. We can use a set instead of an array when we need to ensure that items are unique. Also in sets, there is no defined order. We can define a set using syntax:

Set<Element>

where Element is a type that the set is going to store.

var colorsOfRainBow: Set<String> = ["Red", "orange", "yellow", "green", "blue", "indigo", "violet"]

Modifying the sets

We can use an insert method to insert a new entry.

var favColors: Set<String> = ["Red", "indigo", "violet"]
favColors.insert("green")

We can also remove elements from the set using the remove method which removes the item if it’s present in the set, and returns the removed value, or returns nil if it is not present in the set.

favColors.remove("Red")

There is also a way where we can use an index to remove like this

favColors.remove(at:favColors.firstIndex(of:"Red")!)

Here firstIndex returns the first index where the specified value appears in the collection and then we are passing that index value to the remove method.

Performing Set Operations

We can perform fundamental set operations, such as combining two sets together, checking which values two sets have in common, or determining whether two sets contain all, some, or none of the same values.

  • intersection: The intersection method is used to create a new set with only the values common to both sets.
var colorsOfRainBow: Set<String> = ["Red", "orange", "yellow", "green", "blue", "indigo", "violet"]
var favColors: Set<String> = ["Red", "indigo", "violet","White"]

colorsOfRainBow.intersection(favColors) 

//Result: ["violet", "Red", "indigo"]

The resulting set is made up of the elements that are in both the colorsOfRainBow and favColors sets. Elements that are in only one or the other are left out of the result of the intersection.

  • symmetricDifference: The symmetricDifference method is used to create a new set with values in either set, but not both.
var colorsOfRainBow: Set<String> = ["Red", "orange", "yellow", "green", "blue", "indigo", "violet"]
var favColors: Set<String> = ["Red", "indigo", "violet","White"]

colorsOfRainBow.symmetricDifference(favColors)

//Result: ["orange", "White", "green", "blue", "yellow"]

Here the result set is made up of the elements of the colorsOfRainBow and favColors sets that are not in both colorsOfRainBow and favColors.

  • union: The union method creates a new set with all of the values in both sets.
var colorsOfRainBow: Set<String> = ["Red", "orange", "yellow", "green", "blue", "indigo", "violet"]
var favColors: Set<String> = ["Red", "indigo", "violet","White"]

colorsOfRainBow.union(favColors)

//Result: ["orange", "Red", "indigo", "White", "green", "blue", "yellow", "violet"]

Here we get a set of all the unique values from colorsOfRainBow and favColors sets.

  • subtracting: The subtracting method creates a new set with values, not in the specified set.
var colorsOfRainBow: Set<String> = ["Red", "orange", "yellow", "green", "blue", "indigo", "violet"]
var favColors: Set<String> = ["Red", "indigo", "violet","White"]

colorsOfRainBow.subtract(favColors)
//Result: ["orange", "green", "blue", "yellow"]

Here we get a set of the elements of the colorsOfRainBow set that are not members of the favColors set.

Set membership and equality

There are methods available to check set membership and equality in a swift such as isSubset, isSuperset, isDisjoint.

  • isSubset: The isSubset method determines whether all of the values of a set are contained in the specified set. It returns a boolean value that indicates whether this set is a subset of the given set.

    Set A is a subset of another set B if every member of A is also a member of B.

var colorsOfRainBow: Set<String> = ["Red", "orange", "yellow", "green", "blue", "indigo", "violet"]
var favColors: Set<String> = ["Red", "indigo", "violet","White"]

colorsOfRainBow.isSubset(of: favColors) 
//Result: false

We got a result false as all values from colorsOfRainBow set are not present in favColors set.

  • isSuperSet: The isSuperSet method determines whether a set contains all of the values in a specified set.

    Set A is a superset of another set B if every member of B is also a member of A.

var colorsOfRainBow: Set<String> = ["Red", "orange", "yellow", "green", "blue", "indigo", "violet"]
var favColors: Set<String> = ["Red", "indigo", "violet","White"]

colorsOfRainBow.isSuperset(of: favColors)
//Result: false

Here not all the values from the favColors set are present in colorsOfRainBow so we got the result as false.

  • isDisjoint: The isDisjoint method determines whether two sets have no values in common.
var colorsOfRainBow: Set<String> = ["Red", "orange", "yellow", "green", "blue", "indigo", "violet"]
var favColors: Set<String> = ["Red", "indigo", "violet","White"]

colorsOfRainBow.isDisjoint(with: favColors)
//Result: false

Here we got a result as false because both sets have some values in common.

Tuples

The tuple is used to group multiple values into a single value. The values in a tuple don’t need to be of the same type. We can define tuple by using this syntax

var tupleName: (valueOne:valueOneType, valueTwo:valueTwoType, ...)

We can define tuples for any number of values and with different data types. Also, like an array each value of a tuple has an index that starts from 0.

Consider an example where want user details like name, age, and if user account verified in a single place then we can define a tuple like this

var useDetails: (userName:String, age:Int, isAccountVerified:Bool) = ("UserOne",23, true)

Access values from a tuple

We can access values in the following ways

// Method 1 by using index
useDetails.0
useDetails.1
useDetails.2

// Method 2
useDetails.userName
useDetails.age
useDetails.isAccountVerified

// Method 3
var (userName, userAge, isAccountVerified) = useDetails

Modify tuple values

We can modify values in the following ways

// Method 1 by using index
useDetails.0 = "UserTwo"
// Method 2
useDetails.userName = "UserTwo"

In this article, we explored the collection types in swift like arrays, sets, dictionaries, and tuples. And some methods which we can use to access and modify data stored in those collections.