繁体   English   中英

将1个字典中的项目添加到另一个字典-Swift iOS9

[英]Add items from 1 Dictionary to another Dictionary -Swift iOS9

  1. 我有一个名为buttonPressed的按钮。
  2. 我有一个带有苏打水的sodaArray属性。
  3. 我有一个空的foodDict属性,稍后将其填充键/值对。
  4. 我有一个空的sodaMachineArray属性,必须放入苏打水。我使用一个函数将苏打水附加到其中,然后使用另一个函数为它们分配键/值对,以添加到foodDict中。 我将所有这些都放入了一个名为addSodas()的函数中。

在buttonPressed动作中,首先运行函数addSodas()。 第二,我用不同的值填充foodDict。 我需要将两个字典附加在一起,以便foodDict包含所有苏打水及其当前值。

我遇到的问题是必须首先执行addSodas()函数(我别无选择)。 既然那是第一,而foodDict是第二,那么我该如何结合两个字典呢?

class ViewController: UIViewController {

//soda values already in the sodaArray
var sodaArray = ["Coke", "Pepsi", "Gingerale"]

//I add the soda values to this empty array(I have no choice)
var sodaMachineArray = [String]()

//This is a food dictionary I want to add the sodas in
var foodDict = [String: AnyObject]()


override func viewDidLoad() {
    super.viewDidLoad()
}


//Function to add sodas to the foodDict
func addSodas(){

    //Here I append the sodas into the sodaMachineArray
    for soda in self.sodaArray {
        self.sodaMachineArray.append(soda)
    }

    //I take the sodaMachineArray, grab each index, cast it as a String, and use that as the Key for the key/value pair
    for (index, value) in self.sodaMachineArray.enumerate(){
        self.foodDict[String(index)] = value
    }
    print("\nA. \(self.foodDict)\n")
}


//Button
@IBAction func buttonPressed(sender: UIButton) {

    self.addSodas()
    print("\nB. \(self.foodDict)\n")

    self.foodDict = ["KFC": "Chicken", "PizzaHut": "Pizza", "McDonalds":"Burger"]
    print("\nD. food and soda key/values should print here: \(self.foodDict)???\n")

    /*I need the final outcome to look like this  
self.foodDict = ["0": Coke, "McDonalds": Burger, "1": Pepsi, "KFC": Chicken, "2": Gingerale, "PizzaHut": Pizza]*/
        }
    }

顺便说一句,我知道我可以在下面用此方法扩展Dictionary,但是在这种情况下没有用,因为必须在foodDict填满之前添加addSodas()函数。 此扩展名有效,但我无法在我的方案中使用它。

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

问题:

self.foodDict = ["KFC": "Chicken", "PizzaHut": "Pizza", "McDonalds":"Burger"]

该行创建新数组并分配这些值。

解:

  1. 具有用于保存键值的临时属性[“ KFC”:“ Chicken”,“ PizzaHut”:“ Pizza”,“ McDonalds”:“ Burger”]。
  2. 迭代并将其分配给FoodDict。

例:

//Button
@IBAction func buttonPressed(sender: UIButton) {

    self.addSodas()
    print("\nB. \(self.foodDict)\n")

    var tempFoodDict = ["KFC": "Chicken", "PizzaHut": "Pizza", "McDonalds":"Burger"]
    for (key, value) in tempFoodDict {
        self.foodDict[String(key)] = String(value)
    }
    print("\nD. food and soda key/values should print here: \(self.foodDict)???\n")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM