Json在swift 3传球阵中

时间:2018-02-22 14:47:47

标签: json swift

subject_id=[{"program_id": "1","subject_id":"1"},{"program_id":%20"2","subject_id":"5"}]

我想制作这种类型的json。

这是我的代码我试图改变subject_id但它打印整个数组。我怎么能改变呢。

let subject_id = [String](arrayLiteral: "1","5")

let program_id = [String](arrayLiteral: "1","3")

for program_id in program_id
        {
            print(program_id)
        }

        let phoneNumbersDictionary = program_id.map({ ["program_id": $0 , "subject_id" : $0 ] })


        let JSON = try? JSONSerialization.data(withJSONObject: phoneNumbersDictionary, options: [])

        if let JSON1 = JSON
        {
            print(String(data: JSON1, encoding: String.Encoding.utf8)!)
        }

2 个答案:

答案 0 :(得分:1)

如果您想使用mapzip之前的2个数组。这是工作片段

let pNumbers = zip(subject_ids, program_ids).map { s_id, p_id in ["subject_id": s_id, "program_id": p_id] }

答案 1 :(得分:0)

For-in会更容易:

var index = 0
for pid in program_id {
    array.append(["program_id": pid, "subject_id": subject_id[index]])
    index = index + 1
}

如果你真的想使用map:

let phoneNumbersDictionary = program_id.map({ ["program_id": $0 , "subject_id" : subject_id[program_id.index(of: $0)!]]})

但是我想避免用力解开。