Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Swift Collections - Dictionary
//1. Create
//IMMUTABLE (size and contents cannot be changed)
let immutableResponseMessages = [200: "OK",
403: "Access forbidden",
404: "File not found",
500: "Internal server error"]
//responseMessages[200] = nil //forbidden
//Initialiser Syntax
//var emptyDict1: Dictionary<Int, String> = Dictionary<Int, String>()
//var emptyDict2: Dictionary<Int, String> = [Int: String]()
//var emptyDict3 = [Int: String?]()
//Dictionary Literals Syntax
//var emptyDict4: [Int: String] = [:]
var additionalResponseMessages = [301: "Moved permanently",
200: "Working"]
var mutableResponseMessages = immutableResponseMessages//make mutable copy
//2. Check
let elements = immutableResponseMessages.count
let isEmpty = immutableResponseMessages.isEmpty
//2. Access
let response = immutableResponseMessages[200]
//enumerate with sorted keys
for key in immutableResponseMessages.keys.sorted() {
//enumerate both keys and values in random order
for (key, value) in immutableResponseMessages {
print("Response for: \(key) is '\(value)'")
//enumerate only values (sorted)
for value in immutableResponseMessages.values.sorted() {
//3. Mutate
//mutableResponseMessages[200] = "Very OK"
//let previousValue = mutableResponseMessages.updateValue("Very Very OK", forKey: 200)
//mutableResponseMessages[200] = nil
//let previousValue = mutableResponseMessages.removeValue(forKey: 200)
let merged = immutableResponseMessages.merging(additionalResponseMessages) { (first, second) -> String in
return first
//4. Transform
let errorMessages = merged.filter { (key, value) -> Bool in
return key >= 300
//Dictionary is a Sequence, so it has a map method which produces array.
let values = { $0.value.uppercased() }
//We can still keep dictionary structure using mapValues method.
let mappedDictionary = errorMessages.mapValues { $0.uppercased() }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment