create a hash map in swift in swift

In Swift, you can use the Dictionary data structure to create a Hash Map. Dictionary allows you to store key-value pairs, where each key must be unique. Here's an example of how to create and use a Hash Map in Swift:

main.swift
// Create a new empty dictionary
var hashMap = [String: Int]()

// Add key-value pairs to the dictionary
hashMap["apple"] = 2
hashMap["banana"] = 3
hashMap["orange"] = 5

// Access a value by its key
print(hashMap["apple"])  // Output: Optional(2)

// Update the value of a key
hashMap["banana"] = 4

// Check if a key exists in the dictionary
if let count = hashMap["apple"] {
    print("There are \(count) apples")
} else {
    print("No apples found")
}

// Iterate through the key-value pairs in the dictionary
for (key, value) in hashMap {
    print("\(key): \(value)")
}

// Remove a key-value pair from the dictionary
hashMap.removeValue(forKey: "orange")
663 chars
29 lines

In this example, we've created a new empty dictionary hashMap that maps Strings to Integers. We've added three key-value pairs to the dictionary using the subscript notation []. We've accessed the value associated with the key "apple" using the subscript notation and printed it to the console. We've updated the value associated with the key "banana" using the subscript notation. We've checked if the key "apple" exists in the dictionary using optional binding and printed a message to the console. We've iterated through all key-value pairs in the dictionary using a for-in loop and printed them to the console. Finally, we've removed the key-value pair associated with the key "orange" from the dictionary.

gistlibby LogSnag