Swift Collection types

This week I am summarizing the important methods/concepts I read in the “Collection types” chapter of Swift book. So, let’s get to it :)

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

Collection Types in Swift (from Apple Swift Book)

Arrays
An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions.

Creating an empty array:

var perfectNumbers = [Int]() //https://en.wikipedia.org/wiki/Perfect_number
var names = [String]()

Creating an array with a default value

var threeDoubles = [Double](count: 3, repeatedValue: 0.0)

Appending an array to another array

var anotherThreeDoubles = [Double](count:3, repeatedValue: 2.5)
var sixDoubles = threeDoubles + anotherThreeDoubles

Creating an Array with an Array Literal

var animals = [“Cat”, “Dog”]
var primeNumbers = [1,2,3,5,7]

Accessing and Modifying an Array

This can be done through methods/properties or using the subscript syntax.A couple of useful methods are listed below:

count — Method to find the number of items in the array

isEmpty — Method to find if array is empty

append — Add items to the end of the array

+= operator — Same functionality as the append method

insert(_:atIndex:) — To add an item at a specific index in the array

Subscript index can be used to access/modify an item at a certain index. It can also be used to change a range of values at once even if the replacement set of values have a different length than the original

//animals array = [“Cat”, “Dog”]
if animals.isEmpty {
print("Animals array is empty")
}
else {
print("Animals array contains \(animals.count) animals")
}
animals.append("Lion")
animals += ["Cheetah"]
animals.insert("Tiger",atIndex: 0)
//animals array = ["Tiger",“Cat”, “Dog”,"Lion","Cheetah"]
animals[1] = "Kangaroo"
var firstItem = animals[0] //firstItem = "Tiger"
animals[2...4] = ["Zebra","Elephant"]
//animals array = ["Tiger",“Kangaroo”, "Zebra","Elephant"]

Iterating over an Array

You can iterate over the entire array using the “for-in” loop

for animal in animals {
print(animal)
}

If you need the integer value of index along with the value in the array, use the enumerate method of array which returns a tuple of index and value.

for (index,value) in animals.enumerate() {
print("Animal at index \(index): \(value)")
}

Sets

A set stores distinct/unique values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.

A type must be hashable in order to be stored in a set (must provide a method to compute hash value for itself). A hash value is an Int value that is same for all objects the compare equally (if a==b then hash(a) == hash(b)). All of Swift basic types are hashable and can be used as set values.

Creating an empty Set

var letters = Set<Character>()
//If context is present, you can use [] to create a empty set
letters.insert("c")
letters = [] //letters is empty now

Creating a Set with an Array Literal

var favoritePlaces:Set<String> =[“Vizag”,”Gangtok”,”Seward”,”Seychelles”] //Note that we make the type explicit here! 

A set type cannot be inferred from an array literal, so the type Set must be explicitly set. However, because of Swift’s type inference you can skip the Set type during its initialization. See below for code:

var favoritePlaces_2:Set =[“Vizag”,”Gangtok”,”Seward”,”Seychelles”] //Note that Set type is no longer written here

Accessing and Modifying a Set

A couple of useful methods are listed below:

count — Method to find the number of items in the Set

isEmpty — Method to find if Set is empty

insert(_:) — To insert an entry to the set

remove(_:) — Removes the item from the set if it exists or returns nil if the item is not present in the Set

removeAll(:) — Removes all entries in the Set

contains(_:) — To check if an entry is present in the Set

Here are a few code examples for these methods

//var favoritePlaces:Set =[“Vizag”,”Gangtok”,”Seward”,”Seychelles”]
if favoritePlaces.isEmpty {
print("You have no favorite places. Time to travel 😉")
}
else {
print("You have \(favoritePlaces.count) favorite places.Wow! That's a quite a list.")
}
favoritePlaces.insert("Croatia")
favoritePlaces.remove("Gangtok")
if favoritePlaces.contains("Vizag") {
print("Looks like you have been to the City of Destiny!")
}
else {
print("Make time to visit Vizag! It's scenic and beautiful")
}

Iterating over an Set

Similar to Arrays, we can iterate over a Set using the for-in loop

for place in favoritePlaces { 
print("\(place)")
}
//”Seward”,”Seychelles”,“Vizag”,”Croatia”

Swift’s Set type does not have a defined ordering. To iterate over the items in a specific order, you can use the sort function

for place in favoritePlaces.sort() { 
print("\(place)")
}
//"Croatia","Seward","Seychelles","Vizag"

Dictionary

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order.

Creating an empty dictionary

var namesOfIntegers = [Int: String]()
var stateCapitals = [String:String]()
//If context is known, you can use [:] to make a dictionary empty
stateCapitals["CA"] = "Benecia" //Will explain about this later ;)
stateCapitals = [:]

Creating a Dictionary with a Dictionary Literal

A dictionary literal is similar to an array literal and is a shorthand way of writing key-value pairs as a Dictionary collection. In a dictionary literal, the key and value are separated by a colon.

var stateCapitals:[String:String] = [“CA”: “Benecia”, “OR”:”Salem”]
//Here are the key and value are both of the type String
var stateCapitals = [“CA”: “Benecia”, “OR”:”Salem”]
//Swift infers the type since the dictionary literal values are consistent.

Accessing and Modifying an Dictionary

A couple of useful methods are summarized below:

count — Method to find the number of items in the dictionary

isEmpty — Method to find if dictionary is empty

updateValue(_:forKey:) — To set or update the value for a given key. This function optionally returns the previous value for the key if it was ever set.This method is in addition to the subscript method of updating/setting the value of a key in a dictionary.

removeValueForKey(_:) — To remove a key-value pair from a dictionary. Alternatively, you can use the subscript method and set the value to nil as well.

Code examples for all these methods are given below:

if stateCapitals.isEmpty {
stateCapitals["MT"] = "Helena" //adds a new key-value pair to the dictionary
}
else {
print("Our stateCapitals dictionary has \(stateCapitals.count) entries")
}

if let oldCapital = stateCapitals.updateValue("Sacramento",forKey: "CA") {
print("The old capital of CA was\(oldCapital)")
}
else {
print("There is no old capital for CA!")
}
//prints "The old capital of CA was Benecia" (https://en.wikipedia.org/wiki/Benicia,_California)
stateCapitals["GA"] = "Atlanta"
//stateCapitals = [“CA”: “Sacramento”, “OR”:”Salem", "MT":"Helena","GA":"Atlanta"]
if let removedCapital = stateCapital.removeValueForKey("OR") {
print("The removed capital is \(removedCapital)")
}
else {
print("The dictionary does not contain the capital for OR")
}
stateCapitals["MT"] = nil //This will also remove the MT:Helena entry from the dictionary

Iterating over an Dictionary

for (state,capital) in stateCapitals {
print("Capital for \(state) state is \(capital)")
}

You can also retrieve an iterable collection of dictionary’s keys or values by accessing its keys and values properties

//Iterating through keys
for state in stateCapitals.keys {
print("State: \(state)")
}
//Iterating through capitals
for capital in stateCapitals.values {
print("Capital: \(capital)")
}

Here’s the Swift playground with all the code examples:

https://github.com/prelangi/Swift-Playgrounds/tree/master/SwiftCollections.playground

Like what you read? Give Prasanthi a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.