Dictionary by Example - Swift Programming Language

Overview

  • A collection whose elements are key-value pairs.
  • A dictionary is a type of hash table, providing fast access to the entries it contains.
  • Each entry in the table is identified using its key, which is a hashable type such as a string or number.
  • You use that key to retrieve the corresponding value, which can be any object.
  • In other languages, similar data types are known as hashes or associated arrays.

1. Creating a Dictionary

1.1 init()

  • Creates an empty dictionary.
var emptyDict: [String: String] = [:]
print(emptyDict.isEmpty)

//prints true 

1.2 init(uniqueKeysWithValues:)

  • Creates a new dictionary from the key-value pairs in the given sequence.
let digitWords = ["one", "two", "three", "four", "five"]
let wordToValue = Dictionary(uniqueKeysWithValues: zip(digitWords, 1...5))
print(wordToValue["three"]!)

// Prints 3

print(wordToValue)

// Prints ["three": 3, "four": 4, "five": 5, "one": 1, "two": 2]

1.3 init(_:uniquingKeysWith:)

  • Creates a new dictionary from the key-value pairs in the given sequence, using a combining closure to determine the value for any duplicate keys.
let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
let firstValues = Dictionary(pairsWithDuplicateKeys, uniquingKeysWith: { (first, _) in first })
let lastValues = Dictionary(pairsWithDuplicateKeys, uniquingKeysWith: { (_, last) in last })
print(firstValues)

//prints ["a": 1, "b": 2]

print(lastValues)

//prints ["a": 3, "b": 4]

1.4 init(grouping:by:)

  • Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.
let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })
print(studentsByLetter)

//prints ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]

2. Inspecting a Dictionary

2.1 isEmpty

  • A Boolean value that indicates whether the dictionary is empty.
var frequencies: [String: Int] = [:]
print(frequencies.isEmpty)

// Prints true

2.2 count

  • The number of key-value pairs in the dictionary.
let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })
print(studentsByLetter.count)

//prints 3

2.3 capacity

  • The total number of key-value pairs that the dictionary can contain without allocating new storage.
let dict = Dictionary<String, Any>(minimumCapacity: 20)
print(dict.capacity)

//prints 24

3. Accessing Keys and Values

3.1 subscript(_:)

  • Accesses the value associated with the given key for reading and writing.
var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
print(hues["Coral"])

// Prints Optional(16)

print(hues["Cerise"])

// Prints nil

3.2 index(forKey:)

  • Returns the index for the given key.
let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
let index = countryCodes.index(forKey: "JP")
print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.")

// prints Country code for Japan: 'JP'.

3.3 first

  • The first element of the collection.
let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
if let firstCountry = countryCodes.first {
    print("First value in dictionary is : \(firstCountry)")
}

//prints "First value in dictionary is : (key: "JP", value: "Japan")"

3.4 keys

  • A collection containing just the keys of the dictionary.

for k in countryCodes.keys {
    print(k)
}

// prints BR
// prints JP
// prints GH

3.5 values

  • A collection containing just the values of the dictionary.
let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
print(countryCodes)

// Prints ["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]

for v in countryCodes.values {
    print(v)
}
// Prints Brazil
// Prints Japan
// Prints Ghana

4. Adding Keys and Values

4.1 updateValue(_:forKey:)

  • Updates the value stored in the dictionary for the given key, or adds a new key-value pair if the key does not exist.
if let oldValue = hues.updateValue(18, forKey: "Coral") {
    print("The old value of \(oldValue) was replaced with a new one.")
}

//prints The old value of 16 was replaced with a new one.

4.2 merge(_:uniquingKeysWith:)

  • Merges the given dictionary into this dictionary, using a combining closure to determine the value for any duplicate keys.

var dictionary = ["a": 1, "b": 2]
dictionary.merge(["a": 3, "c": 4]) { (current, _) in current }
print(dictionary)

//prints ["a": 1, "c": 4, "b": 2]

dictionary.merge(["a": 5, "d": 6]) { (_, new) in new }
print(dictionary)

//prints ["a": 5, "b": 2, "d": 6, "c": 4]

4.3 merge(_:uniquingKeysWith:)

  • Merges the key-value pairs in the given sequence into the dictionary, using a combining closure to determine the value for any duplicate keys.
dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current }
print(dictionary)

//prints ["b": 2, "c": 4, "a": 5, "d": 6]

dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new }
print(dictionary)

//prints ["b": 2, "c": 4, "a": 5, "d": 6]

4.4 merging(_:uniquingKeysWith:)

  • Creates a dictionary by merging the given dictionary into this dictionary, using a combining closure to determine the value for duplicate keys.
let otherDictionary = ["a": 3, "b": 4]

let keepingCurrent = dictionary.merging(otherDictionary)
      { (current, _) in current }
print(keepingCurrent)

//prints ["b": 2, "c": 4, "a": 5, "d": 6]

let replacingCurrent = dictionary.merging(otherDictionary)
      { (_, new) in new }
print(replacingCurrent)

//prints ["d": 6, "a": 3, "b": 4, "c": 4]

5. Removing Keys and Values

5.1 removeValue(forKey:)

  • Removes the given key and its associated value from the dictionary.
if let value = hues.removeValue(forKey: "Coral") {
    print("The value \(value) was removed.")
}

//prints The value 18 was removed.

5.2 removeAll(keepingCapacity:)

  • Removes all key-value pairs from the dictionary.
dictionary.removeAll(keepingCapacity: false)
print(dictionary)

//prints [:]

6. Comparing Dictionaries

6.1 ==(::)

let dict1: Dictionary = [1: "one", 2: "two", 3: "three", 4: "four", 5: "five"]
let dict2: Dictionary = [1: "1", 2: "2", 3: "3",4: "4",5: "5"]
if(dict1 == dict2){
	print("equal")	
}else{
	print("Not equal")
}

//prints Not equal

6.2 !=(::)

let dict1: Dictionary = [1: "one", 2: "two", 3: "three", 4: "four", 5: "five"]
let dict2: Dictionary = [1: "1", 2: "2", 3: "3",4: "4",5: "5"]
if(dict1 != dict2){
	print("Not equal")	
}else{
	print("equal")
}

//prints Not equal

7. Iterating over Keys and Values

7.1 forEach(_:)

  • Calls the given closure on each element in the sequence in the same order as a for-in loop.
let numberWords = [1: "one",2: "two", 3: "three"]
for word in numberWords {
    print(word)
}

// Prints (key: 2, value: "two")
(key: 3, value: "three")
(key: 1, value: "one")

numberWords.forEach { word in
    print(word)
}

// Prints (key: 2, value: "two")
(key: 3, value: "three")
(key: 1, value: "one")"

7.2 enumerated()

  • Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.
for (n, c) in numberWords.enumerated() {
    print("\(n)-> 'key:\(c.key) value:\(c.value)'")
}


/* prints 
0-> 'key:2 value:two'
1-> 'key:3 value:three'
2-> 'key:1 value:one' */

8. Finding Elements

8.1 contains(where:)

  • Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
let containsThree = numberWords.contains { (key, value) -> Bool in
	return value == "three"
}
print(containsThree)
//prints true

8.2 first(where:)

  • Returns the first element of the sequence that satisfies the given predicate.

let wordsNumber = ["MinusOne":-1, "zero":0, "one": 1, "two": 2, "three": 3]
if let firstNegative = wordsNumber.first(where: { $0.value < 0 }) {
    print("The first negative number is \(firstNegative).")
}

// prints "The first negative number is (key: "MinusOne", value: -1)."

8.3 min(by:)

  • Returns the minimum element in the sequence, using the given predicate as the comparison between elements.
let leastHue = hues.min { a, b in a.value < b.value }
print(leastHue!)

//prints (key: "Aquamarine", value: 156)

8.4 max(by:)

  • Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue!)

//prints (key: "Heliotrope", value: 296)

9. Describing a Dictionary

9.1 description

  • A string that represents the contents of the dictionary.
print(dict1.description)

//prints [5: "five", 2: "two", 3: "three", 1: "one", 4: "four"]

9.2 debugDescription

  • A string that represents the contents of the dictionary, suitable for debugging.
print(dict1.debugDescription)

//prints [5: "five", 2: "two", 3: "three", 1: "one", 4: "four"]

9.3 customMirror

  • A mirror that reflects the dictionary.
print(dict1.customMirror)

//prints Mirror for Dictionary<Int, String>

You can download the swift playground of all above examples from Here




Related Article