哪个是在swift中创建json对象的最佳方法?

时间:2016-04-08 08:53:34

标签: ios json swift

我试图用字典在swift中创建json对象,但代码越来越长。有没有办法减少例如这段代码的行?您可以看到两个词典都是相同的,除了" id"领域 如果不使用外部库就可以

var product:  [String: String] = [
            "chemical_id":String(activity.chemical!.id),
            "plague_id":String(activity.plague!.id),
            "justification":activity.justification!,
            "amount":activity.amount!,
            "amount_scope":activity.amount_scope!,
            "security_time":activity.security_time!,
            "effectiveness": activity.effectiveness!
        ]
        if activity.id != -1 {
            product = [
                "id":String(activity.id),
                "chemical_id":String(activity.chemical!.id),
                "plague_id":String(activity.plague!.id),
                "justification":activity.justification!,
                "amount":activity.amount!,
                "amount_scope":activity.amount_scope!,
                "security_time":activity.security_time!,
                "effectiveness": activity.effectiveness!
            ]
        }

1 个答案:

答案 0 :(得分:2)

只需在条件

上添加它
if activity.id != -1 {
    product["id"] = String(activity.id)
}