gpt4 book ai didi

swift - 从字典到数组再返回

转载 作者:行者123 更新时间:2023-11-28 15:19:40 25 4
gpt4 key购买 nike

那么,一些背景信息:我使用字典来存储来自已填充 Collection View 的信息,并且字典中的信息与来自 urlsession 的数据配对。

我的字典是这样的:

var allDict = ["Section1": ["device1", "device2"], "Section2": ["device3", "device4"]]

然后我使用一个结构来获取一个数组,该数组提供我的 collectionview 单元格和部分:

struct Objects {
var sectionName : String!
var sectionObjects : [String]!
}
var objectArray = [Objects]()

for (key, value) in allDict {
objectArray.append(Objects(sectionName: key, sectionObjects: value))
}

结果是这样的:

ObjectArray:  [__lldb_expr_134.Objects(sectionName: Section1, sectionObjects: ["device1", "device2"]), __lldb_expr_134.Objects(sectionName: Section2, sectionObjects: ["device3", "device4"])]
["device1", "device2"]

现在,问题是我希望能够重新排列单元格并且能够重新排列数组中的数据,但我必须将其取回字典。我知道字典是未排序的,但是在测试时我从来没有解决过设备在字典内的数组中发生更改的问题。

我的想法是重新排列 ObjectArray,然后清除字典并将数据放回。所以我尝试使用 for 循环从 ObjectArray 取回数据,但我没有做对,这是我尝试过的:

我发现我可以像这样访问数据:

print(objectArray[0].sectionObjects)
["device1", "device2"]

所以我尝试了:

for items in objectArray {
print(items)
for (name) in items.sectionObjects {
print(name)
}
}

我明白了:

device1
device2

但是当我这样做的时候:

for items in objectArray {
print(items)

for (name) in items.sectionName {
print(name)
}
}

我明白了:

S
e
c
t
i
o
n
1

我想要的是:

for (sectionNAme, sectionObjects) in objectArray {
newDictionary[sectionName] += [sectionObjects]
}

但这让我明白了:表达式类型 '[Objects]' is ambiguous without more context

抱歉,文本太长...

最佳答案

你必须这样写循环

for object in objectArray {
newDictionary[object.sectionName] = object.sectionObjects
}

object 表示一个 Objects 实例——顺便说一下,建议以单数形式命名结构 Object——你可以用 object.sectionName 和带有 object.sectionObjects

的对象

注意事项:

S
e
c
t
i
o
n
1

发生是因为您将名称字符串视为数组,并且您正在遍历字符串的字符


由于您无论如何都在使用隐式成员初始化器,因此我会将具有非可选成员的结构声明为 Section 并缩短成员名称:

struct Section {
var name : String
var objects : [String]
}

关于swift - 从字典到数组再返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46242756/

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