I need to convert a Dictionary
with mixed case keys in the same exact Dictionary
but with only lowercase keys.
Here is my attempt (It works but I found this implementation extremely rough)
extension Dictionary {
func lowercaseKeys()->Dictionary<String, AnyObject>{
var newDictionary = Dictionary<String,AnyObject>()
for k in keys{
if let k_string = k as? String{
newDictionary[k_string.lowercaseString] = self[k] as? AnyObject
}
}
return newDictionary
}
}
Can you suggest a more elegant way to solve this problem?
Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value. Let's see an example. If we want to store information about countries and their capitals, we can create a dictionary with country names as keys and capitals as values.
1) Key: In is used to access the value of the element stored in the dictionary. This has to be unique for each element present in the dictionary. Key can be an Integer and String. In terms of swift, these key is often referred to as ‘identifier’ of the element.
As you can see in the above lines of syntax we are creating a blank dictionary in swift. First, we have to give a name to the variable. Followed by the key type and variable type. We will discuss more these two things in detail in the coming section of our tutorial. For now, let’s see one practice syntax to get a better idea see below;
2) Value: This can be anything, also they can be duplicated because we access them by using the key we assign. While creating the value we give the type of the value as well, so they should be of same type throughout the programming for a particular object of dictionary in swift.
Changes its own keys without the need of a temporary dictionary ;)
var dict = ["HEJ":"DÅ", "NeJ":"tack"]
for key in dict.keys {
dict[key.lowercaseString] = dict.removeValueForKey(key)
}
print(dict)
[hej: DÅ, nej: tack]
I made this extension, its a little dirty for now but I will update it again.
extension Dictionary {
mutating func lowercaseKeys() {
for key in self.keys {
let str = (key as! String).lowercaseString
self[str as! Key] = self.removeValueForKey(key)
}
}
}
var dict = ["HeJ":"Då", "nEJ":"taCK!"]
dict.lowercaseKeys()
print(dict)
["hej": "Då", "nej": "taCK!"]
extension Dictionary where Key: StringLiteralConvertible {
mutating func lowercaseKeys() {
for key in self.keys {
self[String(key).lowercaseString as! Key] = self.removeValueForKey(key)
}
}
}
var dict = ["NamE":"David", "LAST_NAME":"Göransson"]
dict.lowercaseKeys() // Will compile
var dict2 = [0:"David", 0:"Göransson"]
dict2.lowercaseKeys() // Won't compile because Key isn't StringLiteralConvertible
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With