Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dictionary 如何将项目字典添加到另一个字典中_Dictionary_Swift - Fatal编程技术网

Dictionary 如何将项目字典添加到另一个字典中

Dictionary 如何将项目字典添加到另一个字典中,dictionary,swift,Dictionary,Swift,Swift中的数组支持+=运算符将一个数组的内容添加到另一个数组中。对于一本字典,有没有一种简单的方法可以做到这一点 例如: 目前,查看for字典,无法轻松地用另一个字典更新一个字典 您可以编写一个扩展来执行此操作 var dict1 = ["a" : "foo"] var dict2 = ["b" : "bar"] extension Dictionary { mutating func update(other:Dictionary) { for (key,valu

Swift中的数组支持+=运算符将一个数组的内容添加到另一个数组中。对于一本字典,有没有一种简单的方法可以做到这一点

例如:

目前,查看for字典,无法轻松地用另一个字典更新一个字典

您可以编写一个扩展来执行此操作

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

extension Dictionary {
    mutating func update(other:Dictionary) {
        for (key,value) in other {
            self.updateValue(value, forKey:key)
        }
    }
}

dict1.update(dict2)
// dict1 is now ["a" : "foo", "b" : "bar]
目前,查看for字典,无法轻松地用另一个字典更新一个字典

您可以编写一个扩展来执行此操作

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

extension Dictionary {
    mutating func update(other:Dictionary) {
        for (key,value) in other {
            self.updateValue(value, forKey:key)
        }
    }
}

dict1.update(dict2)
// dict1 is now ["a" : "foo", "b" : "bar]

它未内置于Swift库中,但您可以通过运算符重载添加所需内容,例如:

func + <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) 
    -> Dictionary<K,V> 
{
    var map = Dictionary<K,V>()
    for (k, v) in left {
        map[k] = v
    }
    for (k, v) in right {
        map[k] = v
    }
    return map
}

它未内置于Swift库中,但您可以通过运算符重载添加所需内容,例如:

func + <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) 
    -> Dictionary<K,V> 
{
    var map = Dictionary<K,V>()
    for (k, v) in left {
        map[k] = v
    }
    for (k, v) in right {
        map[k] = v
    }
    return map
}

您可以为
字典定义
+=
运算符,例如

func += <K, V> (left: inout [K:V], right: [K:V]) { 
    for (k, v) in right { 
        left[k] = v
    } 
}
func+=(左:inout[K:V],右:[K:V]){
对于{
左[k]=v
} 
}

您可以为
字典定义
+=
运算符,例如

func += <K, V> (left: inout [K:V], right: [K:V]) { 
    for (k, v) in right { 
        left[k] = v
    } 
}
func+=(左:inout[K:V],右:[K:V]){
对于{
左[k]=v
} 
}

您可以使用bridgeToObjectiveC()函数使字典成为NSDictionary

将如下所示:

var dict1 = ["a":"Foo"]
var dict2 = ["b":"Boo"]

var combinedDict = dict1.bridgeToObjectiveC()
var mutiDict1 : NSMutableDictionary! = combinedDict.mutableCopy() as NSMutableDictionary

var combineDict2 = dict2.bridgeToObjectiveC()

var combine = mutiDict1.addEntriesFromDictionary(combineDict2)
var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var combinedDict = dict1.mergedWith(dict2)
// => ["a": "foo", "b": "bar"]

然后您可以将NSDictionary(合并)转换回或执行任何操作

您可以使用bridgeToObjectiveC()函数使字典成为NSDictionary

将如下所示:

var dict1 = ["a":"Foo"]
var dict2 = ["b":"Boo"]

var combinedDict = dict1.bridgeToObjectiveC()
var mutiDict1 : NSMutableDictionary! = combinedDict.mutableCopy() as NSMutableDictionary

var combineDict2 = dict2.bridgeToObjectiveC()

var combine = mutiDict1.addEntriesFromDictionary(combineDict2)
var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var combinedDict = dict1.mergedWith(dict2)
// => ["a": "foo", "b": "bar"]
然后您可以将NSDictionary(合并)转换回或执行任何操作

你可以试试这个

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var temp = NSMutableDictionary(dictionary: dict1);
temp.addEntriesFromDictionary(dict2)
你可以试试这个

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var temp = NSMutableDictionary(dictionary: dict1);
temp.addEntriesFromDictionary(dict2)

您还可以使用reduce来合并它们。在操场上试试这个

let d1 = ["a":"foo","b":"bar"]
let d2 = ["c":"car","d":"door"]

let d3 = d1.reduce(d2) { (var d, p) in
   d[p.0] = p.1
   return d
}

您还可以使用reduce来合并它们。在操场上试试这个

let d1 = ["a":"foo","b":"bar"]
let d2 = ["c":"car","d":"door"]

let d3 = d1.reduce(d2) { (var d, p) in
   d[p.0] = p.1
   return d
}
Swift 2.0

extension Dictionary {

    mutating func unionInPlace(dictionary: Dictionary) {
        dictionary.forEach { self.updateValue($1, forKey: $0) }
    }

    func union(var dictionary: Dictionary) -> Dictionary {
        dictionary.unionInPlace(self)
        return dictionary
    }
}
Swift 2.0

extension Dictionary {

    mutating func unionInPlace(dictionary: Dictionary) {
        dictionary.forEach { self.updateValue($1, forKey: $0) }
    }

    func union(var dictionary: Dictionary) -> Dictionary {
        dictionary.unionInPlace(self)
        return dictionary
    }
}
不变的 我更喜欢将不可变字典与
+
运算符组合/合并,因此我实现了如下:

// Swift 2
func + <K,V> (left: Dictionary<K,V>, right: Dictionary<K,V>?) -> Dictionary<K,V> {
    guard let right = right else { return left }
    return left.reduce(right) {
        var new = $0 as [K:V]
        new.updateValue($1.1, forKey: $1.0)
        return new
    }
}

let moreAttributes: [String:AnyObject] = ["Function":"authenticate"]
let attributes: [String:AnyObject] = ["File":"Auth.swift"]

attributes + moreAttributes + nil //["Function": "authenticate", "File": "Auth.swift"]    
attributes + moreAttributes //["Function": "authenticate", "File": "Auth.swift"]
attributes + nil //["File": "Auth.swift"]
//Swift 2
func+(左:字典,右:字典?->Dictionary{
guard let right=right else{返回左侧}
返回左侧。减少(右侧){
var new=$0作为[K:V]
new.updateValue($1.1,forKey:$1.0)
还新
}
}
让moreAttributes:[字符串:AnyObject]=[“函数”:“身份验证”]
let属性:[String:AnyObject]=[“文件”:“Auth.swift”]
attributes+moreAttributes+nil/[“函数”:“身份验证”,“文件”:“Auth.swift”]
attributes+moreAttributes//[“函数”:“身份验证”,“文件”:“Auth.swift”]
attributes+nil/[“文件”:“Auth.swift”]
易变的
//Swift 2
func+=(输入左:字典,右:字典?){
guard let right=right else{return}
right.forEach{key,中的值
updateValue(值,forKey:key)
}
}
让moreAttributes:[字符串:AnyObject]=[“函数”:“身份验证”]
变量属性:[字符串:AnyObject]=[“文件”:“Auth.swift”]
属性+=nil/[“文件”:“Auth.swift”]
attributes+=moreAttributes//[“文件”:“Auth.swift”,“函数”:“authenticate”]
不可变 我更喜欢将不可变字典与
+
运算符组合/合并,因此我实现了如下:

// Swift 2
func + <K,V> (left: Dictionary<K,V>, right: Dictionary<K,V>?) -> Dictionary<K,V> {
    guard let right = right else { return left }
    return left.reduce(right) {
        var new = $0 as [K:V]
        new.updateValue($1.1, forKey: $1.0)
        return new
    }
}

let moreAttributes: [String:AnyObject] = ["Function":"authenticate"]
let attributes: [String:AnyObject] = ["File":"Auth.swift"]

attributes + moreAttributes + nil //["Function": "authenticate", "File": "Auth.swift"]    
attributes + moreAttributes //["Function": "authenticate", "File": "Auth.swift"]
attributes + nil //["File": "Auth.swift"]
//Swift 2
func+(左:字典,右:字典?->Dictionary{
guard let right=right else{返回左侧}
返回左侧。减少(右侧){
var new=$0作为[K:V]
new.updateValue($1.1,forKey:$1.0)
还新
}
}
让moreAttributes:[字符串:AnyObject]=[“函数”:“身份验证”]
let属性:[String:AnyObject]=[“文件”:“Auth.swift”]
attributes+moreAttributes+nil/[“函数”:“身份验证”,“文件”:“Auth.swift”]
attributes+moreAttributes//[“函数”:“身份验证”,“文件”:“Auth.swift”]
attributes+nil/[“文件”:“Auth.swift”]
易变的
//Swift 2
func+=(输入左:字典,右:字典?){
guard let right=right else{return}
right.forEach{key,中的值
updateValue(值,forKey:key)
}
}
让moreAttributes:[字符串:AnyObject]=[“函数”:“身份验证”]
变量属性:[字符串:AnyObject]=[“文件”:“Auth.swift”]
属性+=nil/[“文件”:“Auth.swift”]
attributes+=moreAttributes//[“文件”:“Auth.swift”,“函数”:“authenticate”]

使用扩展名的可读性更强的变体

extension Dictionary {    
    func merge(dict: Dictionary<Key,Value>) -> Dictionary<Key,Value> {
        var mutableCopy = self        
        for (key, value) in dict {
            // If both dictionaries have a value for same key, the value of the other dictionary is used.           
            mutableCopy[key] = value 
        }        
        return mutableCopy
    }    
}
扩展字典{
func合并(dict:Dictionary)->Dictionary{
var mutableCopy=self
用于dict中的(键、值){
//如果两个字典对同一个键都有一个值,则使用另一个字典的值。
可变复制[键]=值
}        
返回可变副本
}    
}

使用扩展名的可读性更强的变体

extension Dictionary {    
    func merge(dict: Dictionary<Key,Value>) -> Dictionary<Key,Value> {
        var mutableCopy = self        
        for (key, value) in dict {
            // If both dictionaries have a value for same key, the value of the other dictionary is used.           
            mutableCopy[key] = value 
        }        
        return mutableCopy
    }    
}
扩展字典{
func合并(dict:Dictionary)->Dictionary{
var mutableCopy=self
用于dict中的(键、值){
//如果两个字典对同一个键都有一个值,则使用另一个字典的值。
可变复制[键]=值
}        
返回可变副本
}    
}

我的需求不同,我需要合并不完整的嵌套数据集,而不会造成混乱

merging:
    ["b": [1, 2], "s": Set([5, 6]), "a": 1, "d": ["x": 2]]
with
    ["b": [3, 4], "s": Set([6, 7]), "a": 2, "d": ["y": 4]]
yields:
    ["b": [1, 2, 3, 4], "s": Set([5, 6, 7]), "a": 2, "d": ["y": 4, "x": 2]]
这比我想的要难。挑战在于从动态类型映射到静态类型,我使用协议来解决这个问题

也值得注意的是,当使用字典文本语法时,实际上得到了基础类型,这些类型不接收协议扩展。我放弃了支持这些元素的努力,因为我找不到一个易于验证集合元素一致性的方法

import UIKit


private protocol Mergable {
    func mergeWithSame<T>(right: T) -> T?
}



public extension Dictionary {

    /**
    Merge Dictionaries

    - Parameter left: Dictionary to update
    - Parameter right:  Source dictionary with values to be merged

    - Returns: Merged dictionay
    */


    func merge(right:Dictionary) -> Dictionary {
        var merged = self
        for (k, rv) in right {

            // case of existing left value
            if let lv = self[k] {

                if let lv = lv as? Mergable where lv.dynamicType == rv.dynamicType {
                    let m = lv.mergeWithSame(rv)
                    merged[k] = m
                }

                else if lv is Mergable {
                    assert(false, "Expected common type for matching keys!")
                }

                else if !(lv is Mergable), let _ = lv as? NSArray {
                    assert(false, "Dictionary literals use incompatible Foundation Types")
                }

                else if !(lv is Mergable), let _ = lv as? NSDictionary {
                    assert(false, "Dictionary literals use incompatible Foundation Types")
                }

                else {
                    merged[k] = rv
                }
            }

                // case of no existing value
            else {
                merged[k] = rv
            }
        }

        return merged
    }
}




extension Array: Mergable {

    func mergeWithSame<T>(right: T) -> T? {

        if let right = right as? Array {
            return (self + right) as? T
        }

        assert(false)
        return nil
    }
}


extension Dictionary: Mergable {

    func mergeWithSame<T>(right: T) -> T? {

        if let right = right as? Dictionary {
            return self.merge(right) as? T
        }

        assert(false)
        return nil
    }
}


extension Set: Mergable {

    func mergeWithSame<T>(right: T) -> T? {

        if let right = right as? Set {
            return self.union(right) as? T
        }

        assert(false)
        return nil
    }
}



var dsa12 = Dictionary<String, Any>()
dsa12["a"] = 1
dsa12["b"] = [1, 2]
dsa12["s"] = Set([5, 6])
dsa12["d"] = ["c":5, "x": 2]


var dsa34 = Dictionary<String, Any>()
dsa34["a"] = 2
dsa34["b"] = [3, 4]
dsa34["s"] = Set([6, 7])
dsa34["d"] = ["c":-5, "y": 4]


//let dsa2 = ["a": 1, "b":a34]
let mdsa3 = dsa12.merge(dsa34)
print("merging:\n\t\(dsa12)\nwith\n\t\(dsa34) \nyields: \n\t\(mdsa3)")
导入UIKit
私有协议Mergable{
func mergeWithSame(右:T)->T?
}
公共扩展词典{
/**
合并词典
-左参数:要更新的字典
-参数右侧:具有要合并的值的源字典
-返回:合并词典
*/
func合并(右:字典)->字典{
var=self
对于右侧的(k,rv){
//退伍军人案件
let sourceDict1 = [1: "one", 2: "two"]
let sourceDict2 = [3: "three", 4: "four"]

let result = sourceDict1.reduce(sourceDict2) { (partialResult , pair) in
    var partialResult = partialResult //without this line we could not modify the dictionary
    partialResult[pair.0] = pair.1
    return partialResult
}
let dict: Dictionary<String, Int> = ["Dog": 1, "Cat": 2]
let dict2: Dictionary<String, Int> = ["Cow": 3]
let dict3: Dictionary<String, Int> = ["Sheep": 4]
$.merge(dict, dict2, dict3)
=> ["Dog": 1, "Cat": 2, "Cow": 3, "Sheep": 4]
dictionaryTwo.forEach {
    dictionaryOne.updateValue($1, forKey: $0)
}
public extension Dictionary {
    public static func +=(lhs: inout [Key: Value], rhs: [Key: Value]) {
        rhs.forEach({ lhs[$0] = $1})
    }
}
public extension Dictionary {

    public static func +=(lhs: inout Dictionary, rhs: Dictionary) {
        for (k, v) in rhs {
            lhs[k] = v
        }
    }

}
  var oldDictionary = ["a": 1, "b": 2]
  var newDictionary = ["a": 10000, "b": 10000, "c": 4]

  oldDictionary.merge(newDictionary) { (oldValue, newValue) -> Int in
        // This closure return what value to consider if repeated keys are found
        return newValue 
  }
  print(oldDictionary) // Prints ["b": 10000, "a": 10000, "c": 4]
let combinedDict = dict1.merging(dict2) { $1 }
extension Dictionary {
    static func += (lhs: inout [Key:Value], rhs: [Key:Value]) {
        lhs.merge(rhs){$1}
    }
    static func + (lhs: [Key:Value], rhs: [Key:Value]) -> [Key:Value] {
        return lhs.merging(rhs){$1}
    }
}
extension Dictionary where Value: Any {
    public func mergeOnto(target: [Key: Value]?) -> [Key: Value] {
        guard let target = target else { return self }
        return self.merging(target) { current, _ in current }
    }
}
var dict1 = ["cat": 5, "dog": 6]
var dict2 = ["dog": 9, "rodent": 10]

dict1 = dict1.mergeOnto(target: dict2)
["cat": 5, "dog": 6, "rodent": 10]

firstDictionary.merge(secondDictionary) { (value1, value2) -> AnyObject in
        return object2 // what you want to return if keys same.
    }
func addAll(from: [String: Any], into: [String: Any]){
    from.forEach {into[$0] = $1}
}