2016-09-08 6 views
1
  1. buttonPressedという名前のボタンが1つあります。
  2. 私はそれにソーダを持つsodaArrayプロパティを持っています。
  3. 私は後でキーと値のペアで塗りつぶした空のfoodDictプロパティを持っています。
  4. 私はソーダを入れなければなりません。ソーダを入れておきます。ソーダを関数に追加し、別の関数を使用してキー/値のペアを割り当ててfoodDictに追加します。私はこれをaddSodas()という名前の関数の中に入れました。

buttonPressedアクションでは、最初に関数addSodas()を実行します。第二に、私は食べ物をいっぱいにします。 foodDictにすべてのソーダが入っているように、両方の辞書を一緒に追加する必要があります。1辞書から別の辞書に項目を追加する - スクロールiOS9

私が抱えている問題は、addSodas()関数が最初に来なければならないということです(私には選択肢がありません)。それが最初で食べ物辞書は二番目ですから、どうすれば両方の辞書を組み合わせることができますか?

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()funcはfoodDictがいっぱいになる前に来る必要があるため、このような状況では使用ません。この拡張機能は動作しますが、私のシナリオでは使用できません。

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

順序は重要ではありません。 – vadian

+0

私はdictが順序付けられていないことを知っています。しかし、ありがとう:) –

答えて

6

問題:

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

この行は、新しい配列を作成し、それらの値を割り当てます。

ソリューション:

  1. は、キーの値を保持するための一時的な性質を持っている[ "KFC": "チキン"、 "PizzaHut": "ピザ"、 "マクドナルド": "バーガー"]。
  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") 
} 
+0

ありがとう!意味あり :) –

関連する問題