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

Populate a struct array with unique identifier

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

    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 数据 我想用 serviceData 数据填充 arrServices 的值。

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

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 的新手,我无法解决这个问题,我们将不胜感激任何建议和帮助。

您应该检查以前的服务 ID:

if loadedServices.contains { (element) -> Bool in
        element.id == currentService.id
    }) == false { 
        // unique
        loadedServices.append(currentService)
        ...
    } else { 

    } 

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

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

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

}