如何在Swift中维护Dictionary中数据的顺序?

问题描述 投票:0回答:2

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

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

      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
2个回答
0
投票

字典没有特定顺序


0
投票

简短回答:

您无法维持Dictionary中的顺序。

长回答:

苹果说:

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

请参考this

要保持顺序,您需要使用Array或从sorted创建Array Dictionary(升序,降序或通过使用特定键进行使用。

谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.