扩展字典,其中Key是String类型 [英] Extend Dictionary where Key is of type String
本文介绍了扩展字典,其中Key是String类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想扩展一个Dictionary的方法,但只有当Key是String类型时。
I want to have extend a method of Dictionary but only if Key is of type String.
我尝试这样做:
extension Dictionary where Key: String {
mutating func lowercaseKeys() {
for key in self.keys {
self[key.lowercase] = self.removeValueForKey(key)
}
}
}
并得到错误:
键入'Key'约束到非协议类型'String'
Type 'Key' constrained to non-protocol type 'String'
根据这个错误信息,我可以告诉我只能用协议进行这种过滤...有没有办法绕过这个? p>
Based on this error message I can tell that I can only do this kind of filtering with protocols... Is there a way to by-pass this?
推荐答案
我相信最符合您需求的协议是 StringLiteralConvertible
有几条额外的行,将让你完成这个
I believe the closest protocol that meets your needs is StringLiteralConvertible
, which, with a few extra lines, will let you accomplish this
extension Dictionary where Key: StringLiteralConvertible {
mutating func setAllKeysLowercase() {
for key in self.keys {
if let lowercaseKey = String(key).lowercaseString as? Key {
self[lowercaseKey] = self.removeValueForKey(key)
}
}
}
}
var stringKeyDictionary = [ "Hello" : NSObject(), "World" : NSObject() ]
stringKeyDictionary.setAllKeysLowercase()
print( stringKeyDictionary )
// Prints: ["hello": <NSObject: 0x1007033c0>, "world": <NSObject: 0x1007033d0>]
var numberKeyDictionary = [ 0 : NSObject(), 1: NSObject() ]
numberKeyDictionary.setAllKeysLowercase() //< Won't compile, keys are not strings
这篇关于扩展字典,其中Key是String类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文