将对象追加到数组中,使用Swift将数组存储在字典中

时间:2016-05-03 14:46:23

标签: swift

我有一个包含两个部分的字典。有一个类型Int的值为0,另一个值为1.在第0节中我想要一个沙龙数组。沙龙是一个自定义对象。第1节还将有一系列沙龙。

以下是代码:

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 个答案:

答案 0 :(得分: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;
}

<强>解释

以这种方式初始化词典:

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

该指令创建一个没有元素的对象 所以,迭代:

 dictionary[0]?.append(salon)

会发生什么?

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