字典扩展返回组合字典 [英] Dictionary extension to return a combined dictionary

查看:132
本文介绍了字典扩展返回组合字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以下列方式扩展Swift的字典类:

I'm trying to extend Swift's dictionary class in the following manner:

extension Dictionary {

    func merge<K, V>(dict: [K:V]) -> Dictionary<K, V> {
        var combinedDict: [K:V] = [:]
        for (k, v) in self {
            combinedDict[k] = v
        }

        for (k, v) in dict {
            combinedDict[k] = v
        }

        return combinedDict
    }



}

第一个for循环给了我错误:can not subscript类型为'[K:V]'的类型为'Key'的值,但第二个for循环很好。我甚至评论了第一个检查,第二个仍然工作。任何人知道问题是什么?谢谢!

The first for loop gives me the error: "Cannot subscript a value of type '[K:V]' with an index of type 'Key'" but the second for loop is fine. I even commented out the first one to check and the second still works. Anyone know what the problem is? Thanks!

推荐答案

字典类型已定义 Key Value 作为通用变量,因此不需要$(code> K 和 V 导致问题)。

The dictionary type already defines Key and Value as generic variables, so K and V are not required (and cause the problem).

extension Dictionary {
    func merge(dict: [Key : Value]) -> [Key : Value] {
        var combinedDict = self

        for (k, v) in dict {
            combinedDict[k] = v
        }

        return combinedDict
    }
}

这篇关于字典扩展返回组合字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆