gpt4 book ai didi

ios - Swift如何访问嵌套结构中的信息?

转载 作者:行者123 更新时间:2023-12-01 19:37:17 26 4
gpt4 key购买 nike

我有一个带有主题和子主题信息的大嵌套结构数据文件。

struct Topic{
struct Topic1{
let name = "Topic 1"
let description = "Topic 1 description here."

struct SubtopicUniqueName1 {
let title = "Subtopic title here."
let subtopicDescription = "Some lorem ipsum description...."
let subtopicContent = ["First Sentence", "Second Sentence", "Hello"]
}

struct SubtopicUniqueName2 {
let title = "Subtopic title here."
let subtopicDescription = "Some lorem ipsum description...."
let subtopicContent = ["First Sentence", "Second Sentence", "Hello"]
}
}

struct Topic2{
let name = "Topic 2"
let description = "Topic 2 description here."
struct SubtopicUniqueName3 {
let title = "Subtopic title here."
let subtopicDescription = "Some lorem ipsum description...."
let subtopicContent = ["First Sentence", "Second Sentence", "Hello"]
}
}
}

我想得到一个包含Topic1,Topic2等所有“名称”的数组,以此类推,因为最后我将有多达14个主题。当我尝试 let allTopics = [Topic.Topic1, Topic.Topic2]时它将无法运行

我想通过做类似的事情来获取信息
for i in allTopics{
print(i().name)
}

最后,由于Subtopics结构进一步嵌套,我是否可以在Topic中以类似的方式访问其内容?

最佳答案

您会混淆值和类型。在这里,您实际上只有两种类型:主题和子主题。因此,让他们:

struct Topic {
let name: String
let description: String
let subTopics: [SubTopic]
}

struct SubTopic {
let title: String
let description: String
let content: [String]
}

其他所有内容只是这两种类型之一的实例:
let topics = [
Topic(
name: "Topic 1",
description: "Topic 1 description here.",
subTopics: [
SubTopic(
title: "Subtopic title here.",
description: "Some lorem ipsum description...",
content: ["First Sentence", "Second Sentence", "Hello"]
),
SubTopic(
title: "Subtopic title here.",
description: "Some lorem ipsum description...",
content: ["First Sentence", "Second Sentence", "Hello"]
),
]
),
Topic(
name: "Topic 2",
description: "Topic 2 description here.",
subTopics: [
SubTopic(
title: "Subtopic title here.",
description: "Some lorem ipsum description...",
content: ["First Sentence", "Second Sentence", "Hello"]
),
]
),
]

由于这些只是常规数组,因此您可以轻松地对其进行迭代:
for topic in topics {
print("\(topic.name) - \(topic.description)")
print()

for subTopic in topic.subTopics {
let content = subTopic.content.joined(separator: "\n\t")
print("""
\(subTopic.title) - \(subTopic.description)
\(content)

""")
}
}

输出:
Topic 1 - Topic 1 description here.

Subtopic title here. - Some lorem ipsum description...
First Sentence
Second Sentence
Hello

Subtopic title here. - Some lorem ipsum description...
First Sentence
Second Sentence
Hello

Topic 2 - Topic 2 description here.

Subtopic title here. - Some lorem ipsum description...
First Sentence
Second Sentence
Hello

关于ios - Swift如何访问嵌套结构中的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59760143/

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