我想按顺序显示数据。我正在获取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
}
。
字典没有特定顺序
您无法维持Dictionary
中的顺序。
苹果说:
字典是键-值关联的无序集合。
请参考this
要保持顺序,您需要使用Array
或从sorted
创建Array
Dictionary
(升序,降序或通过使用特定键进行使用。
谢谢。