我想扩展一个Dictionary的方法,但只有当Key是String类型时.
我试着这样做:
extension Dictionary where Key: String { mutating func lowercaseKeys() { for key in self.keys { self[key.lowercase] = self.removeValueForKey(key) } } }
并得到错误:
Type ‘Key’ constrained to non-protocol type ‘String’
基于这个错误信息,我可以告诉我只能用协议进行这种过滤…有没有办法绕过这个?
我相信最符合您需求的协议是StringLiteralConvertible,其中有几个额外的行将让您完成此操作
原文链接:https://www.f2er.com/swift/319641.htmlextension 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