【发布时间】:2017-01-16 21:59:50
【问题描述】:
- 我有一个名为 buttonPressed 的按钮。
- 我有一个 sodaArray 属性,里面有苏打水。
- 我有一个空的 foodDict 属性,稍后我用键/值对填充该属性。
- 我有一个空的 sodaMachineArray 属性,我必须将苏打水放入其中。我使用一个函数将苏打水附加到其中,然后使用另一个函数为其分配键/值对以添加到 foodDict。我把这些都放在了 1 个名为 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]*/
}
}
顺便说一句,我知道我可以使用下面的这种方法扩展字典,但在这种情况下它没有用,因为 addSodas() 函数必须在 foodDict 被填满之前出现。此扩展程序有效,但我无法将其用于我的场景。
extension Dictionary {
mutating func appendThisDictWithKeyValuePairsFromAnotherDict(anotherDict:Dictionary) {
for (key,value) in anotherDict {
self.updateValue(value, forKey:key)
}
}
}
【问题讨论】:
-
顺序无关紧要,因为字典无论如何都是无序的。
-
我知道字典是无序的。不过谢谢:)
标签: ios arrays swift loops dictionary