To create an empty dictionary in Swift, you can use the `Dictionary` type with specific key and value types or shorthand syntax. A dictionary is a collection of key-value pairs where each key must be unique.
We can create an empty dictionary in Swift where the keys are integers and the values are strings. This example demonstrates how to initialize an empty dictionary and add key-value pairs to it.
For example,
myDictionary
with integer keys and string values.var myDictionary: [Int: String] = [:]
// Add key-value pairs to the dictionary
myDictionary[1] = "One"
myDictionary[2] = "Two"
myDictionary[3] = "Three"
// Print the dictionary contents
print("Dictionary contents:")
for (key, value) in myDictionary {
print("Key: \(key), Value: \(value)")
}
Dictionary contents: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can create an empty dictionary in Swift where the keys are strings and the values are doubles. This example demonstrates how to initialize an empty dictionary and add key-value pairs to it.
For example,
myDictionary
with string keys and double values.var myDictionary: [String: Double] = [:]
// Add key-value pairs to the dictionary
myDictionary["A"] = 1.1
myDictionary["B"] = 2.2
myDictionary["C"] = 3.3
// Print the dictionary contents
print("Dictionary contents:")
for (key, value) in myDictionary {
print("Key: \(key), Value: \(value)")
}
Dictionary contents: Key: A, Value: 1.1 Key: B, Value: 2.2 Key: C, Value: 3.3
In this tutorial, we learned How to create an Empty Dictionary in Swift language with well detailed examples.