gpt4 book ai didi

swift - 使用 Swift 将对象附加到数组中,其中数组存储在字典中

转载 作者:行者123 更新时间:2023-11-30 13:27:20 24 4
gpt4 key购买 nike

我有一本字典,它有两个部分。有一个 Int 类型的节,其值为 0,另一个节的值为 1。在节 0 中,我想要一个 Salons 数组。其中 Salons 是自定义对象。第 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 个元素。我哪里出错了?

最佳答案

此代码是您所需要的:

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

关于swift - 使用 Swift 将对象附加到数组中,其中数组存储在字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37007343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com