在数组中追加结构元素

时间:2018-10-11 10:27:16

标签: ios swift struct codable

我有一个结构,想要获取其中的元素数量并将值附加到数组中,但是找不到一种方法。

object

}

我正在使用它来显示和更新基于后端响应的UISwitch值。最好的方法是什么?下面是解码JSON响应后的输出,我希望将所需的输出作为字典[[String:Bool]]的数组。

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用镜子:

let pref = User_notification_preferences(comments: true, likes: false, dislikes: nil, unfollow: true, follow: nil, updates: false)

let prefMirror = Mirror(reflecting: pref)

var switchStatus: [String:Bool] = [String:Bool]()

prefMirror.children.forEach { child in
    guard let label = child.label else {
        fatalError("Couldn't get the label")
    }
    switchStatus[label] = child.value as? Bool ?? false
}

print(switchStatus) //["follow": false, "updates": false, "unfollow": true, "dislikes": false, "likes": false, "comments": true]

即使您修改了User_notification_preferences的属性,这也将起作用。

或者,您可以使用像这样的天真的函数:

struct User_notification_preferences : Codable {
    //...
    func dictionaryRepresentation() -> [String:Bool] {
        return ["comments": comments ?? false,
                "likes": likes ?? false,
                "dislikes": dislikes ?? false,
                "unfollow": likes ?? false,
                "follow": likes ?? false,
                "updates": likes ?? false
        ]
    }
}

并像这样使用它:

print(pref.dictionaryRepresentation()) //["follow": false, "updates": false, "comments": true, "likes": false, "dislikes": false, "unfollow": false]

答案 1 :(得分:0)

您可以将其编码为键值对,然后获取所需的内容:

let userNotiPre  = User_notification_preferences()
let jsonDatas = try JSONEncoder().encode(userNotiPre)

if let dict = try JSONSerialization.jsonObject(with: jsonDatas, options: []) as? [String: Hashable]{
   //Get all values from dict and then you can also get count of that array 
   let array = dict.values
   array.count
}