Dictionary in Swift

Where? How does the Swift compiler store values in a Dictionary?

Photo by Dmitry Ratushny on Unsplash

Prerequisites:

Terminology

What is a dictionary

A dictionary with Integer keys and Values

Initializing

var myDictionary: [Int: Int] = [:]
var myDictionary = [Int: Int]()

Adding values to a dictionary

myDictionary[4] = 17
myDictionary[8] = 7

Changing values in a dictionary

myDictionary[4] = 11
myDictionary.updateValue(1, forKey: 0) // return nil

Retrieving values in a dictionary

let studentFour: Int? = myDictionary[4] // 11
let studentFive: Int? = myDictionary[5] // nil

Increment values in a dictionary: default values

myDictionary[4]! += 1 // 12
myDictionary[8]! += 1 // 8
myDictionary[5]! += 1 // error
myDictionary[5, default: 0] += 1

Iterate through values in a dictionary

for pupil in myDictionary {
print (pupil.key, pupil.value)
}

Sorting a dictionary

myDictionary.sorted{
return $0.value > $1.value
}

Filtering a dictionary

myDictionary.filter{return $0.key % 2 == 0}

General dictionaries

Creating combinations of Int and String Dictionaries

var intstring = [1: "a"] // [Int: String]
var stringint = ["a": 1] // [String: Int]
var intint = [1: 1] // [Int: Int]
var stringstring = ["a": "a"] // [String: String]

Copy on write

var mySecondDictionary = myDictionary
print (myDictionary, mySecondDictionary)
// [4: 12, 8: 8, 5: 1] [4: 12, 8: 8, 5: 1]

Why use dictionaries

Conclusion

Extend your knowledge

The Twitter contact:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store