首页 > 解决方案 > Swift - 遍历结构数组

问题描述

这是非常基本的,我有点不好意思问,但是......我正在从我的服务器检索一些 JSON 到这些结构中:

struct CategoryInfo: Codable {
    var categoriesResult: [CategoryDetail]
}

struct CategoryDetail: Codable{
    var categoryName: String
    var categoryDescription: String
    var categorySortOrder: Int
    var categoryId: String
}

现在我想为这几十个事件中的每一个循环遍历 CategoryDe​​tail,将它们保存到 CoreData 中。我目前的尝试如下所示:

            let decoder = JSONDecoder()
            do {
                let categories = try decoder.decode(CategoryInfo.self, from: data!)
                for category in [CategoryDetail] {
                    //... perform the CoreData storage here
                }

但是我收到 CategoryDe​​tail 不符合 Sequence 或 IterateProtocol 的错误,但是当我尝试实现这些时,坦率地说,解决方案显得太复杂了。它只是一个数组......我不应该能够在没有很多hoohaw的情况下循环它(当然,在技术意义上使用它)?

标签: jsonswiftstruct

解决方案


请仔细看看你的结构

您正在解码CategoryInfo结构

let categoryInfo = try decoder.decode(CategoryInfo.self, from: data!)

并且类别在categoriesResult成员中

for category in categoryInfo.categoriesResult {
    //... perform the CoreData storage here
}

推荐阅读