我试图用字典在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!
]
}
答案 0 :(得分:2)
只需在条件
上添加它if activity.id != -1 {
product["id"] = String(activity.id)
}