json - Swift - 遍历结构数组
问题描述
这是非常基本的,我有点不好意思问,但是......我正在从我的服务器检索一些 JSON 到这些结构中:
struct CategoryInfo: Codable {
var categoriesResult: [CategoryDetail]
}
struct CategoryDetail: Codable{
var categoryName: String
var categoryDescription: String
var categorySortOrder: Int
var categoryId: String
}
现在我想为这几十个事件中的每一个循环遍历 CategoryDetail,将它们保存到 CoreData 中。我目前的尝试如下所示:
let decoder = JSONDecoder()
do {
let categories = try decoder.decode(CategoryInfo.self, from: data!)
for category in [CategoryDetail] {
//... perform the CoreData storage here
}
但是我收到 CategoryDetail 不符合 Sequence 或 IterateProtocol 的错误,但是当我尝试实现这些时,坦率地说,解决方案显得太复杂了。它只是一个数组......我不应该能够在没有很多hoohaw的情况下循环它(当然,在技术意义上使用它)?
解决方案
请仔细看看你的结构
您正在解码CategoryInfo
结构
let categoryInfo = try decoder.decode(CategoryInfo.self, from: data!)
并且类别在categoriesResult
成员中
for category in categoryInfo.categoriesResult {
//... perform the CoreData storage here
}
推荐阅读
- python - 我正在我的 discord.py 机器人上创建一个警告功能,但我不知道为什么它会给我一个属性错误
- django - 为什么我的 Django 登录没有通过身份验证?
- magit - 如何将 libegit2 与 Magit 一起使用
- kubernetes - 将 IAM 角色从 EKS 中的 Pod 附加到 Serviceaccount
- shell - Curl GET 请求未在正文中提供任何输出
- sql - 月度数据未正确反映
- racket - 不知道如何解决这个错误 [Racket]: "car: contract violation expected: pair? given: '()"
- c - 我不能在从函数返回的 char 指针上使用 free()
- django - Django AWS S3 - 400“错误请求” - 无法从存储桶访问图像
- sql - 在数据库中我的查询得到第一行当我分组时