Basics | Arrays | Colors | Date and Time | Dictionaries | Sets | Sorting | Strings | Functional Swift
var dictionary:[String:String] = [:] // Empty
dictionary = ["AAPL": "Apple",
"MSFT": "Microsoft",
"AMZN": "Amazon",
"GOOG": "Google"]
let sharesOwned = ["AAPL": 200, "MSFT": 50] // [String:Int]let n = dictionary.countlet appleLongName = dictionary["AAPL"]!
print("\(appleLongName)")func dumpDictionary() {
for (key, value) in dictionary {
print("\(key), \(value)")
}
}
dumpDictionary()Value might not exist so we wrap in let
if let value = dictionary["AAPL"] {
print("Found value for key = \(value)")
} else {
dictionary["AAPL"] = "Apple" // Add
}if dictionary["AAPL"] == nil {
dictionary["AAPL"] = "Apple"
}dictionary["GOOGL"] = "Alphabet"dictionary.keysdictionary.removeValue(forKey: "GOOG")
dictionary["AAPL"] = nil
dictionary.count
let sortedKeys = Array(dictionary.keys).sorted(by: <)for (key, value) in dictionary.sorted(by: { $0.0 < $1.0 }) {
// let value = dictionary[key]
print("=>\(key), \(value)")
}dictionary.updateValue("Alpha", forKey: "ALPHA")
dumpDictionary()dictionary.removeAll()