我需要在同一个完全字典中转换带有混合大小写字典的字典,但只使用小写字母.
这是我的尝试(它有效,但我发现这个实现非常粗糙)
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 } }
无需临时字典即可更改自己的密钥;)
原文链接:https://www.f2er.com/swift/318590.htmlvar dict = ["HEJ":"DÅ","NeJ":"tack"] for key in dict.keys { dict[key.lowercaseString] = dict.removeValueForKey(key) } print(dict)
[hej: DÅ,nej: tack]
编辑
我做了这个扩展,现在它有点脏,但我会再次更新它.
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!”]
编辑2
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