Swift –Collection Types
Collection Types
Swift has three primary collection types, they are arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values and Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value pair.
Arrays, sets, and dictionaries in Swift are everytime clear about the types of values and keys that they can store in the program. This means that you cannot insert a value of the wrong type into a collection by mistake. So it means that we can be confident about the type of values that will be retrieved from a collection.
Mutability of Collections
By creating an array, a set, or a dictionary, when assigning it to a variable, the collection that is created will be mutable so the value can be modified at runtime. So the programmer can perform (or mutate) operation of by adding, removing, or changing items in the collection after it is created. If an array, a set, or a dictionary is assigned to a constant, that collection will be immutable, and its size and contents cannot be changed once assigned.
It is better practice to create immutable collections in all situations where the collection does not need to change at all. It will optimize the performance of the collections you create which will be good for the project.
Arrays
An array stores values in an ordered list of the same type. The same value can appear in an array multiple times at different positions, So it can contain a duplicate value.
Swift’s Array type is attached or can say bridged to Foundation’s NSArray class.
Creating an Empty Array
You can create an empty array of a any type using initializer syntax using:
var someInteger = [Int]()
print(“someInts is of type [Int] with \(someInteger.count) items.”)
// Prints “someInts is of type [Int] with 0 items.”
Creating an Array with a Default Value
Swift’s Array type also provides a way for creating an array of a fixed size with all of its values set to the same value i.e default. You can pass this initializer a default value of the appropriate type using repeating(called repeating): and the number of times that value is repeated in the new array using count (called count):
var threeDoubles = Array(repeating: 1.230, count: 3)
// threeDoubles is of type [Double], and equals [1.230, 1.230, 1.230]
Creating an Array by Adding Two Arrays Together
We can create a new array by adding together two existing arrays having right compatible types with the addition operator (+). The new array’s type is inferred from the type of the two arrays that we have used to add together:
var another_ThreeDoubles = Array(repeating: 2.56, count: 3)
// another_ThreeDoubles is of type [Double], and equals [2.56, 2.56, 2.56]
var six_Doubles = threeDoubles + anotherThreeDoubles
// six_Doubles is inferred as [Double], and equals [1.230, 1.230, 1.230, 2.56, 2.56, 2.56]
Creating an Array with an Array Literal
We can also initialize an array with an array (string) literal, which is a way to write one or more values as an array collection. An array literal is can be represented as a list of values, separated by commas, enveloped by a pair of square brackets:
[value 1, value 2, value 3]
The example below creates an array called shoppingList to store the String values:
var shopping_List: [String] = [“Egg”, “MilkyBar”]
// shopping_List has been initialized with two initial items
The shoppingList variable is declared as an array of string values, represented as [String]. Because this particular array contains value type of String, it is allowed to store String values only currently. As we can see, the shoppingList array is initialized with two String values only they are “Eggs” and “Milk”, written within an array literal.
Iterating Over an Array
We can iterate over the entire set of values present in an array with the for-in loop:
for item in shopping_List {
print(item)
}
OUTPUT
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
for (index, value) in shopping_List.enumerated() {
print(“Item \(index + 1): \(value)”)
}
OUTPUT
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
Sets
Set stores unique values of the same type in a collection with no defined ordering in it. We can use a set instead of an array when the order of items is not so important, or when you need to ensure that an item only appears once in the variable.
Set Type Syntax
The type of a Swift set is represented as Set<Element>, where Element is the type that the set is allowed to store in the program.
Creating and Initializing an Empty Set
For creating an empty set of specific type use initializer syntax as follows:
var letters_set = Set<Character>()
print(“letters_set is of type Set<Character> with \(letters_set.count) items.”)
// Prints “letters_set is of type Set<Character> with 0 items.”
To create an empty set with an empty array literal is as follows :
letters_set.insert(“a”)
// letters now contains 1 value of type Character
letters_set = []
// letters is now an empty set, but is still of type Set<Character>
Creating a Set with an Array Literal
To initialize a set with an array literal, one another way to write one or more values as a set collection is as follows.
The example below creates a set called favorite_Genres to store String values:
var favorite_Genres: Set<String> = [“Rock”, “Classical”, “Hip hop”]
// favorite_Genres has been initialized with three initial items
For more about the for-in loop with a set.
Swift’s Set type does not have a defined ordering. To iterate over the values present in set in a specific order, use the sorted() method, which returns the set’s elements as an array sorted using the < operator.
for genre in favorite_Genres.sorted() {
print(“\(genre)”)
}
// Classical
// Hip hop
// Jazz
Fundamental Set Operations
The below figure depicts two sets a set and b set with the results of various set operations represented by the light green shaded regions.
Set Membership and Equality
The below figure depicts three sets—a set, b set, and c set—with overlapping regions representing elements shared among different sets. Set a is a superset of set b because a contains all elements present in b. Conversely, set b is a subset of set a, because all elements in b are also present in a. Set b and set c are disjoint with one another because they share not even single elements is common.
Dictionaries
A dictionary stores pair of value, which is between keys of the same type and values of the same type in a collection with no defined ordering. Every value is associated with a unique key, which acts as an identifier for that value within the dictionary. Items in an array have specified order but items in a dictionary do not have a specified order. Dictionary is used when you need to look up values based on their identifier, it’s similar to a real-world dictionary is used to see the definition for a particular word.
Creating an Empty Dictionary
For arrays, you can create an empty Dictionary of a certain type.
Initalizer syntax as follows :
var namesOf_Integers = [Int: String]()
// namesOf_Integers is an empty [Int: String] dictionary
Above eg. creates an empty dictionary of type [Int: String] to store names of integer values which have keys of type Int, and values are of type String.
If the context already provides type information, we can create an empty dictionary with an empty dictionary literal, which is represented as follows [:] (a colon inside a pair of square brackets):
namesOf_Integers[16] = “sixteen”
// namesOf_Integers now contains 1 key-value pair
namesOf_Integers = [:]
// namesOf_Integers is once again an empty dictionary of type [Int: String]
Creating a Dictionary with a Dictionary Literal
We can also initialize a dictionary with a dictionary literal, which has a syntax similar to the array literal that we have seen earlier.
A key-value pair is a combination of a key and a value with the unique key. In a dictionary literal, the key and value in every key-value pair are separated by a colon. The key-value pairs are represented as a list, separated by commas, enveloped by a pair of square brackets:
[key 1: value 1, key 2: value 2, key 3: value 3]
Below example creates a dictionary to store the names of international airports. Dictionary represents keys are three-letter International Air Transport Association codes, and the values are airport names:-
var airports: [String: String] = [“LAU”: “Lamu Lamu”, “DUB”: “Dublin”]
The airport’s dictionary is declared as having a type of [String: String], which means keys are of type String, and whose values are also of type String, both are of the same Datatype”.
To remove a key-value pair from a dictionary use removeValue(forKey:) method. This method removes the key-value pair if it exists and returns the removed value, or returns nil if no value existed:
if let removed_Value = airports.remove_Value(forKey: “DUB”) {
print(“The removed airport name is \(removed_Value).”)
} else {
print(“The airports dictionary does not contain a value for DUB.”)
}
// Prints “The removed airport name is Dublin Airport.”
Iterating Over a Dictionary
To iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple or pair, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:
for (airportCodes, airportName) in airports {
print(“\(airportCodes): \(airportName)”)
}
// YYZ: Toronto Pearson
// DWR: Dresden Germany
About the for-in loop
To retrieve an iterable collection of a dictionary’s keys or values we can use its keys and values properties:
for airportCodes in airports.keys {
print(“Airport codes: \(airportCodes)”)
}
// Airport code: YYZ
// Airport code: DWR
for airportName1 in airports.values {
print(“Airport name: \(airportName1)”)
}
// Airport name: Toronto Pearson
// Airport name: Dresden Germany