Swift Как получить доступ к информации во вложенных структурах? - PullRequest
1 голос
/ 16 января 2020

У меня есть большой вложенный файл данных структуры с информацией Topi c и Subtopi c.

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)
}

Наконец, потому что структуры подрубрик вложены еще дальше, буду ли я получать доступ к их содержимому подобным образом в топи c?

Ответы [ 2 ]

1 голос
/ 16 января 2020

Вы путаете значения и типы. У вас есть только два типа: темы и подтемы. Итак, давайте сделаем их:

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

1 голос
/ 16 января 2020

тип allTopics - [Любой], который скрывает члена определенного класса c.

Решение:

Создание протокола со свойством name и любые другие интересующие вас свойства и примените их к структурам, которые должны иметь эти свойства, затем создать коллекцию объектов, которые реализуют протокол. Коллекция может быть повторена, а свойства протокола доступны без приведения.

let allTopics: [TopicName] = [Topic.Topic1(), Topic.Topic2()]
allTopics.forEach {
    print($0)
}

protocol TopicName {
    var name: String { get }
}

struct Topic{
    struct Topic1: TopicName {
      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: TopicName {
        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"]
        }
    }
}
...