arraysswiftswifty-json

How to convert array to dictionary with SwiftyJSON?


I restructured my endpoint return and want my front end code to work with the old way. I have 3 values in an array and would like to convert it to a dictionary [Int64: JSON]. I'm using SwiftyJSON. Thank you.

What I have:

let time = JSON(rawValue: x)!.int64Value                   //1614748500
let like = point["val"].int64Value                         //91
let dislike = JSON.init(integerLiteral: trend.rawValue)    //3

// po print(array) [1614748500, 91, 3]
                    0 element

// po arrray ▿ 3 elements
             - 0 : 1614748500
             - 1 : 91
             - 2 : 3

What I want it to be

 //  po print(array) [1614748500: [
                 1614748500,
                 91,
                 3
                 ]
                 0 element

 //  po array ▿ 1 elements
              ▿ 0 : 2 elements
              - key : 1614748500
              ▿ value : [
                1614748500,
                91,
                3
               ]
             ▿ rawArray : 3 elements
             - 0 : 1614748500
             - 1 : 91
             - 2 : 3
             - rawDictionary : 0 elements
             - rawString : ""
             - rawNumber : 0
             - rawNull : <null>
             - rawBool : false
             - type : SwiftyJSON.Type.array
             - error : nil

Solution

  • Took me a while finally figured it out.

    var dict = [Int64: JSON]()
    
    let time = JSON(rawValue: x)!.int64Value                   //1614748500
    let like = point["val"].int64Value                         //91
    let dislike = JSON.init(integerLiteral: trend.rawValue)    //3
    
    dict[time] = JSON(arrayLiteral: time, like, dislike)
    
     po print(dict)
        [1614748500: [
        1614748500,
        91,
        3
        ]