2016-05-03 11 views
0

私は2つのセクションを持つ辞書を持っています。セクションタイプIntには値0があり、セクション1には値1があります。セクション0ではサロンの配列が必要です。サロンはカスタムオブジェクトです。セクション1には、サロンの配列もあります。Swiftを使って配列が辞書に格納されている配列にオブジェクトを追加する

func getListOfSalons() -> NSDictionary { 

    //I create the dictionary here. 
    var dictionary = [Int:[Salon]](); 

    //I got to my repo to get an Array holding Salon Objects 
    let salonsArray = self.repository.getListOfSalons(); 

    var count = 0; 
    var section = 0; 

    //I then iterate through salonsArray to get each salon 
    for salon in salonsArray { 

     //This code will determine when to switch to new section 
     //Ultimately there will only be 3 salons in Secion 0 
     if(count > 3 && section == 0){ 
      section += 1; 
     } 

     dictionary[section]?.append(salon); 
     count += 1; 
    } 

    return dictionary; 
} 

私は現在が午前問題は、辞書は常に0の要素を持っていることである。ここでは

コードがあります。どこが間違っていますか?

+1

ループで実際にsalonsArrayが使用されているかどうか確認しましたか? self.repository.getListOfSalons()はどのように実装されていますか? – Moritz

+0

"salonsArray"をデバッグしましたか?それは数が0以上の[Saloon]ですか? –

答えて

0

このコードは何が必要です:

func getListOfSaloons() -> NSDictionary { 
    var salonsArray = self.repository.getListOfSalons(); 
    var dictionary = NSMutableDictionary() 

    var count = 0; 
    var section = 0; 

    for salon in salonsArray {  
     if(count > 3 && section == 0){ 
      section += 1; 
     } 
     if dictionary[section] == nil { 
      dictionary[section] = NSMutableArray() 
     } 
     var salons = dictionary[section] as! [Salon] 
     salons.append(salon) 
     dictionary[section] = salons 
    } 
    count += 1; 
    return dictionary; 
} 

説明:

あなたは、このように辞書をINIT:

var dictionary = [Int:[Salon]](); 

この命令は、要素を持たないオブジェクトを作成します。
ので、反復:起こる

dictionary[0]?.append(salon) 

何?

dictionary[0] => is nil 
?.append(salon) => will never executed 
関連する問題