2016-05-03 8 views
0

ist Ich habe ein Wörterbuch, das zwei Abschnitte hat. Es gibt einen Abschnittstyp Int mit dem Wert 0 und einen anderen Abschnitt mit dem Wert 1. In Abschnitt 0 möchte ich ein Array von Salons haben. Wo Salons ein benutzerdefiniertes Objekt ist. Abschnitt 1 wird auch eine Reihe von Salons haben. HierEin Objekt in Array einfügen, wo das Array in einem Wörterbuch mit Swift

ist der Code:

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; 
} 

Das Problem, das ich derzeit habe, dass das Wörterbuch immer 0 Elemente hat. Wo gehe ich falsch?

+1

Haben Sie überprüft, ob salonsArray tatsächlich gefüllt ist, wenn Ihre Schleife es verwendet? Wie ist self.repository.getListOfSalons() implementiert? – Moritz

+0

haben Sie "salonsArray" debugged? ist es ein [Saloon] mit count> 0? –

Antwort

0

Dieser Code ist, was Sie brauchen:

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; 
} 

Erläuterung:

Sie init Wörterbuch auf diese Weise: ein Objekt ohne Elemente

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

Diese Anweisung erstellen.
So Iterieren:

dictionary[0]?.append(salon) 

was passiert?

dictionary[0] => is nil 
?.append(salon) => will never executed