我们需要在 [String:String]
类型的字典中添加键值对,其中我尝试添加的值可能是可选的,但我需要确保与具有值的可选值配对被添加到字典中,其他的被简单地丢弃。
我已经尝试为此在字典上创建一个扩展。
extension Dictionary {
mutating func insert(stringOptinal optional : String?, forStringKey stringKey : String) {
if let stringValue = optional {
self[stringKey as! Key] = stringValue as? Value
}
}
}
var dictionary = ["1":"One","2":"Two"]
var serverFetchedStringWithString : String? = "Some String From Server,That ay or may not exists"
var serverFetchedStringWithNil : String?
//Added as key value pair
dictionary.insert(stringOptinal: serverFetchedStringWithString, forStringKey: "3")
// Not added
dictionary.insert(stringOptinal: serverFetchedStringWithNil, forStringKey: "4")
print(dictionary)
var dictionaryOfIntString = [1:"One",2:"Two"]
//An obvious crash as we are trying to insert [String:String] to a dictionary of [Int,String]
dictionaryOfIntString.insert(stringOptinal: serverFetchedStringWithString, forStringKey: "3")
这适用于类型为 [String:String]
的所有字典。但是当类型改变时崩溃(例如 [Int:String]
)。
编辑:我添加的扩展是通用版本,它对具有 Hashable 键和值的字典有效。如何确保此扩展适用于 [String: String]
ONLY 类型的词典。
如何确保此扩展仅对 [String:String]
类型的词典有效?
最佳答案
您可以通过如下声明来限制您的字典扩展仅适用于 StringLiteralConvertable
的键和值:
extension Dictionary where Key: StringLiteralConvertible, Value: StringLiteralConvertible {
mutating func insert(stringOptinal optional : String?, forStringKey stringKey : String) {
if let stringValue = optional {
self[stringKey as! Key] = stringValue as? Value
}
}
}
您的示例随后会生成编译器错误,但至少不会崩溃。
关于swift - 键和值具有特定类型的字典类型的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37546267/