Dictionary
Dictionary
Init
Different types to initialize
let dict = [String: Int](/404)
let dict2: [String: Int] = [
"Kautilya": 0,
"Zeus": 1,
"Sensehack": 2,
]
let dict3: [String: Int]?
var initProtocol = [String : Int](/404)
someProtocol["one"] = 1
someProtocol["two"] = 2
let someProtocol = [
"one" : 1,
"two" : 2
]
Access
Traversing
for (key, value) in dictionaryName {
// Depending on types you would parse or type cast these data types while printing or utilizing.
print("Key: \(key) & value: \(value)")
}
Complexity
Search
Searching time is always constant in Dictionary as they are hashed internally, so the key is accepted in any common hashable data type and Swift compiler internally generates a Hash value for it. So it’s easy to get those details.
Quirks
Thats the reason that Dictionary aren’t organized in a sorted manner.
Update
It’s also in constant Big O(1) time.
Applications
- Great for generating a hash map or keeping track of things in computer science.
- Different data types can be utilized.
- Great for real life enterprise scenarios where restful APIs returns a mix of primitive types in JSON data format.
convert Dictionary Values to Array
Could be replaced with compactMap { $0 } as well
let colors = colorsForColorScheme.values.flatMap { $0 }
Or
let colors = Array(dict.values)
Or
let colors = colorsForColorScheme.map { $0.1 }
References
https://stackoverflow.com/questions/26988167/swift-dictionary-get-values-as-array