To swap keys and values in a dictionary in Swift, you can use a `for` loop to iterate through the original dictionary and add each key-value pair to a new dictionary with the key and value swapped. This allows you to create a new dictionary where the keys and values are swapped.
We can swap keys and values in a dictionary in Swift using a `for` loop. This example demonstrates how to declare and initialize a dictionary, use a `for` loop to swap the keys and values, and print the resulting dictionary.
For example,
originalDict
with integer keys and string values.swappedDict
to store the swapped key-value pairs.var originalDict: [Int: String] = [
1: "One",
2: "Two",
3: "Three"
]
// Declare an empty dictionary to store the swapped key-value pairs
var swappedDict: [String: Int] = [:]
// Use a for loop to swap the keys and values
for (key, value) in originalDict {
swappedDict[value] = key
}
// Print the resulting dictionary
print("Swapped dictionary:")
for (key, value) in swappedDict {
print("Key: \(key), Value: \(value)")
}
Swapped dictionary: Key: One, Value: 1 Key: Two, Value: 2 Key: Three, Value: 3
We can swap keys and values in a dictionary with duplicate values in Swift by checking for duplicates and handling them appropriately. This example demonstrates how to declare and initialize a dictionary with duplicate values, use a `for` loop to swap the keys and values while handling duplicates, and print the resulting dictionary.
For example,
originalDict
with integer keys and string values, including duplicate values.swappedDict
to store the swapped key-value pairs, with arrays as values to handle duplicates.var originalDict: [Int: String] = [
1: "One",
2: "Two",
3: "One"
]
// Declare an empty dictionary to store the swapped key-value pairs
var swappedDict: [String: [Int]] = [:]
// Use a for loop to swap the keys and values
for (key, value) in originalDict {
if swappedDict[value] == nil {
swappedDict[value] = [Int]()
}
swappedDict[value]?.append(key)
}
// Print the resulting dictionary
print("Swapped dictionary:")
for (key, value) in swappedDict {
print("Key: \(key), Values: \(value)")
}
Swapped dictionary: Key: One, Values: [1, 3] Key: Two, Values: [2]
In this tutorial, we learned How to Swap Keys and Values in a Dictionary in Swift language with well detailed examples.