Декодируйте файлы json и добавьте их в массив

Я хочу декодировать несколько файлов JSON и добавить их в массив. Я использую этот код для этого:

struct SearchDetailSections: Decodable {
    var detailSections: [SearchDetailSection]
}

struct SearchDetailSection: Decodable {
    let title, translation, transcription : String
}

class SearchViewController: UIViewController {

var searchDetailSection = [SearchDetailSection]()

func decodeSection() {
        
        for index in 1...21 {
            let url = Bundle.main.url(forResource: "\(index)", withExtension: "json")!
            let data = try! Data(contentsOf: url)
            let result = try! JSONDecoder().decode(SearchDetailSections.self, from: data)
            let a = result.detailSections.count - 1
            
            for sections in 0...a {
                searchDetailSection.append(result.detailSections[sections])
            }
            
            print(searchDetailSection)
        }
    }
}

У меня есть 21 файл json, который выглядит так:

1.json

{
    "detailSections" : [
        
        {

            "index": 1,
            "translation":"text",
            "title":"text",
            "transcription":"2 text,

        },

        etc

    ]
}

2.json

{
    "detailSections" : [
        
        {

            "index": 1,
            "translation":"text",
            "title":"text",
            "transcription":"text",

        },

        etc

    ]
}

В своем коде я использую несколько циклов для добавления файла в массив. Является ли правильный и лучший способ решить мою задачу? Или мне нужно использовать другой способ?


50
1

Ответ:

Решено

Вы можете сгладить декодированный массив, используя flatMap или reduce. Подход FlatMap может выглядеть так

let detailedSections = (1...21).map { index in
    let url = Bundle.main.url(forResource: "\(index)", withExtension: "json")!
    let data = try! Data(contentsOf: url)
    return try! JSONDecoder().decode(SearchDetailSections.self, from: data)
}.flatMap { sections in
    return sections.detailSections
}

// Use detailedSections here, which is of type [SearchDetailSection]
// for example:
self.searchDetailSection = detailedSections