swift – 扩展字典,其中Key是String类型

前端之家收集整理的这篇文章主要介绍了swift – 扩展字典,其中Key是String类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想扩展一个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,其中有几个额外的行将让您完成此操作
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
原文链接:https://www.f2er.com/swift/319641.html

猜你在找的Swift相关文章