ios - 使用唯一标识符填充结构数组

标签 ios swift struct swifty-json

这是我的场景,我得到了一个服务列表,在该服务列表中,一个服务可以包含多个属性,所以我创建了以下结构

    var serviceData : JSON = [
    "services": [
        [
            "id": "SERVICE ONE ID",
            "properties": [
                [
                "id": "propetyID",
                "name": "first service first property name"
                ],
                [
                    "id": "propetyID",
                    "name": "first service second property name"
                ]
            ],
            "name": "First Service"
        ],
        [
            "id": "SERVICE Two ID",
            "properties": [
                [
                "id": "propetyID",
                "name": "second service first property name"
                ],
                [
                    "id": "propetyID",
                    "name": "second service second property name"
                ]
            ],
            "name": "Second Service"
        ]
    ]   
]
struct Properties {
    var id:String
    var name:String
}
struct Services {
    var id:String
    var name:String
    var properties:[Properties]
}
var arrServices : [Services]()

我正在使用 SwiftyJSON并创建了上面的 json我要填充 arrServices 的值的数据与 serviceData数据。

并且我希望服务数据是唯一的,例如第一个服务有两个属性,因此服务结构数组的第一个索引应该如下所示(伪代码):

struct Services
    id:SERVICE ONE ID
    name:First Service
    properties: [Properties(id:"propertyID",name:"first service first property name"),Properties(id:"propertyID",name:"first service second property name")]

我是 swift 的新手,我无法全神贯注地解决这个问题,我们将不胜感激任何建议和帮助。

最佳答案

你有一个字典数组,所以你可以这样解析它:

 for dict in json["services"].arrayValue {

    arrServices.append(
        Services(
            id: dict["id"].stringValue,
            name: dict["name"].stringValue,
            properties: dict["properties"].arrayValue.map {
                Properties(
                    id: $0["id"].stringValue,
                    name: $0["name"].stringValue
                )
            }
        )
    )

}

关于ios - 使用唯一标识符填充结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57789840/

相关文章:

在链表中创建数据类型为 "struct"的新节点

go - 如何访问未导出的结构字段

ios - 为 iPhone 生成唯一 ID

ios - 在 UITextview 中获取点击的单词

ios - 在 ios Objective-c 的 mapview 上添加带有多个图像的多个注释?

swift - 每个 View Controller 在屏幕右侧都有空白

c - C 中的结构和指针

iphone - 在 iphone 中从数据库中检索图像花费的时间太长

ios - 不能将字典安全放入变量

ios - 从 Firebase 数据库异步方法返回值