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

问题描述 投票:0回答:2

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

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 {struct Topic1 {let name =“ Topic 1” let description =“ Topic 1 description here”。 ...

ios swift struct nested
2个回答
1
投票

allTopics的类型是[Any],它隐藏特定类的成员。


1
投票

您正在混淆值和类型。在这里,您实际上只有两种类型:主题和子主题。因此,让我们制作它们:

© www.soinside.com 2019 - 2024. All rights reserved.