Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Collections - Dictionary
//DICTIONARIES
//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
//MUTABLE
//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() {
print(immutableResponseMessages[key]!)
}
//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() {
print(value)
}
//3. Mutate
//UPDATE
//mutableResponseMessages[200] = "Very OK"
//let previousValue = mutableResponseMessages.updateValue("Very Very OK", forKey: 200)
//print(mutableResponseMessages[200]!)
//REMOVE
//mutableResponseMessages[200] = nil
//let previousValue = mutableResponseMessages.removeValue(forKey: 200)
//MERGE
let merged = immutableResponseMessages.merging(additionalResponseMessages) { (first, second) -> String in
return first
}
print(merged)
//4. Transform
let errorMessages = merged.filter { (key, value) -> Bool in
return key >= 300
}
//print(errorMessages)
//Dictionary is a Sequence, so it has a map method which produces array.
let values = merged.map { $0.value.uppercased() }
//print(values)
//We can still keep dictionary structure using mapValues method.
let mappedDictionary = errorMessages.mapValues { $0.uppercased() }
print(mappedDictionary)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment