【问题标题】:How to maintain the order of the data in Dictionary in Swift?如何在 Swift 中维护 Dictionary 中数据的顺序?
【发布时间】:2019-12-23 07:33:54
【问题描述】:

我想按顺序显示数据。我将 json 字符串作为响应并转换为字典。转换字典后我无法维持顺序。 我知道我们使用字典时不能保证顺序。
如何维护数据的实际顺序。

注意:我无法对密钥进行硬编码,因为数据来自服务器响应。

      func setupData(responseString : String)
      {
           // Convert string to dictionary for extracting the keys and values
           // Need to maintain the order while adding the data
           let content = convertToDictionary(text: responseString)
           var text : String = ""
           if let contentDataDict = content
           {
                 for (key, value) in  contentDataDict
                 {
                      // want to append the key and values in the sequence order
                        content +=  \(key) \n \(value)
                  }

            }
            textView.attributedText = text.htmlToAttributedString

     } 

【问题讨论】:

  • 创建一个字典数组并使用它

标签: ios swift sequence nsdictionary


【解决方案1】:

简答:

你不能在Dictionary维护秩序。

长答案:

苹果说:

字典是键值关联的无序集合。

请参考this

要保持顺序,您需要使用Array 或从Dictionary 创建sorted Array(升序、降序或使用特定键)并使用它。

谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 2012-04-12
    相关资源
    最近更新 更多