【问题标题】:How to convert array to dictionary with SwiftyJSON?如何使用 SwiftyJSON 将数组转换为字典?
【发布时间】:2021-03-03 20:44:44
【问题描述】:

我重组了我的端点返回并希望我的前端代码以旧方式工作。我在一个数组中有 3 个值,并希望将其转换为字典 [Int64: JSON]。我正在使用 SwiftyJSON。谢谢。

我有什么:

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

我想要它是什么

 //  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

【问题讨论】:

  • 那么错误/问题是什么?你被困在哪里了?
  • 不,没有错误。我只是不知道如何将它从一个数组转换为喜欢数组的底部。 :(
  • 你应该用谷歌搜索,你应该能够修复它。作为提示,我不确定。似乎数组的每个第一个元素都必须是字典的键。因此,获取第一个索引元素,使其成为键并将该数组分配回去。
  • 我确实查过了,但两天都找不到解决方案,所以我希望 SOF 能够提供帮助。
  • 如何你想将你的数组转换成字典?这其中的逻辑还不是很清楚?

标签: arrays swift swifty-json


【解决方案1】:

因此,您有一个包含 3 个元素的数组,并希望将其转换为具有三个键值对的字典。为此,您首先决定将使用哪些键。可能是“第一”、“第二”和“第三”,但希望你有更有意义的键。然后你像这样转换:

let array = [“string1”, “string2”, “string3”]
let dict = [“first”: array[0], “second”: array[1], “third”: array[2]]

就是这样。而且真的不需要第三方的 JSON 库。

而且 [Int64: JSON] 肯定不是字典。字典 = 键/值对。对于 JSON 字典,键必须是字符串。

【讨论】:

    【解决方案2】:

    花了我一段时间终于弄明白了。

    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
        ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多