iosswiftsequencensdictionary

How to maintain the order of the data in Dictionary in Swift?


I want to display the data in the sequence order. I am getting the json string as the response and converted into the Dictionary. I am not able to maintain the order after converted dictionary. I know it's not guaranteed the order when we use dictionary.
How do I maintain the actual order of the data.

Note: I can't hard code the key since data's are coming from the server response.

      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

     } 

.


Solution

  • Short answer:

    You can not maintain order in the Dictionary.

    Long answer:

    Apple says:

    Dictionaries are unordered collections of key-value associations.

    Please refer this

    To maintain the order you need to use the Array or create sorted Array(Ascending, Descending or by using specific key) from the Dictionary and use it.

    Thank you.