Swift中的小写字典键

时间:2015-10-16 12:51:15

标签: swift

我需要在同一个Dictionary中使用混合大小写字母转换Dictionary,但只使用小写键。

这是我的尝试(它有效,但我发现这个实现非常粗糙)

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
    }
}

你能建议一种更优雅的方法来解决这个问题吗?

5 个答案:

答案 0 :(得分:6)

更改自己的密钥而无需临时字典;)

var 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

答案 1 :(得分:2)

像这样的Smth?

  var dict = ["KEY": "value"]
  var newDict = [String: AnyObject]()

  for (key, value) in dict {
     newDict[key.lowercaseString] = value
  }

答案 2 :(得分:2)

Arbitur的回答,针对Swift 3进行了更新:

extension Dictionary where Key: ExpressibleByStringLiteral {
    public mutating func lowercaseKeys() {
        for key in self.keys {
            self[String(describing: key).lowercased() as! Key] = self.removeValue(forKey: key)
        }
    }
}

答案 3 :(得分:0)

这是我的解决方案,没有强制铸造,完全安全。

protocol LowercaseConvertible {
    var lowercaseString: Self { get }
}

extension String: LowercaseConvertible {}

extension Dictionary where Key: LowercaseConvertible {
    func lowercaseKeys() -> Dictionary {
        var newDictionary = Dictionary()

        for k in keys {
            newDictionary[k.lowercaseString] = self[k]
        }
        return newDictionary
    }
}

答案 4 :(得分:-1)

作为循环的替代方法,您可以使用map函数:

func lowercaseKeys () -> Dictionary<String, AnyObject> {
    var newDictionary = Dictionary<String,AnyObject>()
    Array(keys).map { key in
        newDictionary[(key as! String).lowercaseString] = self[key] as? AnyObject
    }
    return newDictionary
}