- 我有一个名为 buttonPressed 的按钮。
- 我有一个 sodaArray 属性,里面有苏打水。
- 我有一个空的 foodDict 属性,稍后我用键/值对填充它。
- 我有一个空的 sodaMachineArray 属性,我必须将苏打水放入其中。我使用一个函数将苏打水附加到其中,然后使用另一个函数为它们分配键/值对以添加到 foodDict 中。我把这一切都放在 1 个名为 addSodas() 的函数中。
在 buttonPressed Action 中,我首先运行函数 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]*/
}
}
顺便说一句,我知道我可以用下面的这个方法扩展字典,但在这种情况下它没有用,因为 addSodas() 函数必须在 foodDict 填满之前出现。此扩展有效,但我无法将其用于我的方案。
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"]
此行创建新数组并分配这些值。
解决方案:
- 有一个临时属性来保存键值 ["KFC": "Chicken", "PizzaHut": "Pizza", "McDonalds":"Burger"]。
- 迭代并将其分配给 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")
}
关于ios - 将 1 个词典中的项目添加到另一个词典 -Swift iOS9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399918/