Swift Quiz #06 - Swift Sets and Dictionaries

Topics: Swift Sets and Swift Dictionaries

Follow us on

Swift Sets:

  • Set is a collection that stores distinct values of the same type with no defined ordering.

  • Set is a collection that stores distinct values of the same type with no defined ordering. It is useful when the order of items doesn’t matter, and each item should appear only once.

  • Sets require elements to be hashable, which means they must provide a way to compute a hash value.

Creating a Set:

  • An empty set can be created using the initializer syntax

  • Alternatively, an empty set can be created with an empty array literal if the context provides type information.

  • A set can also be initialized with values using a set literal

    var letters = Set<Character>() // Initializer
    letters = []  // empty literal but still Set<Character>
    var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] // Set Literal

Accessing and Modifying a Set:

  • The number of items in a set can be checked using the count property.

  • To add an item to a set, the insert(_:) method can be used

  • To remove an item, the remove(_:) method can be used.

  • To check if a set contains a particular item, the contains(_:) method can be used.

    print("The count is \(favoriteGenres.count).")  // Count
    
    favoriteGenres.insert("Jazz") // Insert
    
    if let removedGenre = favoriteGenres.remove("Rock") {
        print("\(removedGenre)? No longer a favorite.")   // Remove
    }
    
    if favoriteGenres.contains("Funk") {          // Contains 
        print("I enjoy funk music.")
    } else {
        print("Not a fan of funk.")
    }

Iterating Over a Set:

  • Values in a set can be iterated using a for-in loop

  • To iterate in a specific order, the sorted() method can be used:

    // for..in
    for genre in favoriteGenres {
        print("\(genre)")
    }
    
    // sorted
    for genre in favoriteGenres.sorted() {
        print("\(genre)")
    }

Set Operations:

Various set operations can be performed, such as union, intersection, subtraction, and symmetric difference

    let oddDigits: Set = [1, 3, 5, 7, 9]
    let evenDigits: Set = [0, 2, 4, 6, 8]
    let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
    
    oddDigits.union(evenDigits).sorted()  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    oddDigits.intersection(evenDigits).sorted() // // []
    oddDigits.subtracting(singleDigitPrimeNumbers).sorted()  // [1, 9]
    oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted() // [1, 2, 9]

Set Membership and Equality:

A set can be checked if it is a subset, superset, or disjoint with another set, or if two sets are equal.

    let houseAnimals: Set = ["🐶", "🐱"]
    let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
    let cityAnimals: Set = ["🐦", "🐭"]
    
    houseAnimals.isSubset(of: farmAnimals) // true
    farmAnimals.isSuperset(of: houseAnimals) // true
    farmAnimals.isDisjoint(with: cityAnimals) // true

Swift Dictionaries:

  • Dictionary stores associations between keys and values of the same type. Each value is associated with a unique key.

  • Keys must be hashable, and Swift provides shorthand syntax for creating dictionaries.

Creating a Dictionary:

  • An empty dictionary can be created using initializer syntax.

  • Alternatively, an empty dictionary can be created with an empty dictionary literal if the context provides type information

  • A dictionary can also be initialized with values using a dictionary literal:

    var namesOfIntegers: [Int: String] = [:]  
    
    var namesOfIntegers = [:]   // dictionary literals
    
    var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

Accessing and Modifying a Dictionary:

  • To access the value associated with a key, subscript syntax can be used

  • The subscript syntax can be used to add or update

  • removeValue(forKey:) can be used to remove the values

    if let airportName = airports["YYZ"] {
        print("The airport is named \(airportName).")    // read       
    }
    
    airports["LHR"] = "London Heathrow" 
    
    if let removedValue = airports.removeValue(forKey: "DUB") {
        print("The removed airport is named \(removedValue).")
    }   // remove 

Iterating Over a Dictionary:

  • To iterate over the key-value pairs in a dictionary, a for-in loop can be used

  • To iterate over keys or values only, the keys or values property can be used.

    for (airportCode, airportName) in airports {
        print("\(airportCode): \(airportName)")
    }
    
    for airportCode in airports.keys {
        print("Airport code: \(airportCode)").  // keys
    }
    for airportName in airports.values {
        print("Airport name: \(airportName)")   // values
    }

Quizzes

1. Which code snippet correctly declares an empty set of integers in Swift?

a) var set: Set<Int> = {}

b) var set: Set<Int> = []

c) var set = Set<Int>()

Answer: c) var set = Set<Int>()

a) declares an empty dictionary instead of a set. Option b) initializes an empty array instead of a set. Option c) correctly initializes an empty set of integers.

2. What does the following code snippet do?

var dict = ["apple": 3, "banana": 5, "orange": 2]
dict["banana"] = nil

a) Adds a new key-value pair to the dictionary.

b) Removes the key-value pair “banana” from the dictionary.

c) Updates the value associated with the key “banana”

Answer: b) Removes the key-value pair “banana” from the dictionary.

Assigning nil to a dictionary's key using subscript notation removes the key-value pair from the dictionary. In the given code, the key-value pair with the key "banana" is removed from the dictionary.

3. What will be the output of the following code snippet?

let set1: Set<Int> = [1, 2, 3, 4, 5]
let set2: Set<Int> = [1, 2]
let isSuperset = set1.isSuperset(of: set2)
print(isSuperset)

a) true

b) false

c) Compilation error

Answer: a) true

The isSuperset(of:) method is used to check if a set is a superset of another set, meaning it contains all the elements of the other set. In the given code, isSuperset will be true because set1 contains all the elements of set2.

4. What will be the output of the following code snippet?

let set1: Set<String> = ["Apple", "Banana", "Orange"]
let set2: Set<String> = ["Banana", "Orange", "Apple"]
let areEqual = set1 == set2
print(areEqual)

a) true

b) false

Answer: a) true

Sets in Swift are unordered collections, so the order of elements doesn’t matter. In the given code, areEqual will be true because set1 and set2 contain the same elements.

5. What is the output?

let set1: Set<String> = ["Apple", "Banana", "Orange"]
let set2: Set<String> = ["Banana", "Orange", "Apple"]
let isStrictSubset = set1.isStrictSubset(of: set2)
print(isStrictSubset)

a) true

b) false

Answer b)false

isStrictSubset(of:) method determines whether a set is a subset but not equal to, a specified set.

6. What is the output?

var dictionary: [String: [Int]] = ["Fruits": [1, 2, 3], "Vegetables": [4, 5, 6]]
let values = Array(dictionary.values.joined())
print(values.count)

a) 3

b) 6

c) 9

d) 12

Answer: b) 6

By using the joined() method on the values collection, we create a single array containing all the elements from the arrays. The count of the resulting array is 6.

7. What is the output?

let set1: Set<Int> = [1, 2, 3, 4]
let set2: Set<Int> = [3, 4, 5, 6]
let symmetricDifference = set1.symmetricDifference(set2)
print(symmetricDifference.count)

a) 0

b) 1

c) 2

d) 4

Answer: d) 4

The symmetric difference method returns a new set with elements that are either in set1 or set2, but not in both. In this case, the elements in the symmetric difference set are 1, 2, 5, and 6, resulting in a count of 4.

8. What is the output?

let set1: Set<Int> = [1, 2, 3 ]
let set2: Set<Int> = [1, 2, 3, 4, 5]
let isStrictSubset = set1.isStrictSubset(of: set2)
print(isStrictSubset)

a) true

b) false

Answer: a) true

The isStrictSubset(of:) method is used to determine whether a set is a subset, and all elements are present. Here it is true.

9. What is the difference between superset and strictSuperset?

a) superset checks if a set contains all the elements of another set, while strictSuperset checks if a set is a proper superset of another set.

b) superset checks if a set contains all the elements of another set, while strictSuperset checks it is not equal to, a specified set.

c) superset checks if a set is a proper superset of another set, while strictSuperset checks if a set contains all the elements that are not of another set.

Answer: b) superset checks if a set contains all the elements of another set, while strictSuperset checks it is not equal to, a specified set.