0

There are items that are based on an order in JSON that need to be returned in that specific order if their bool is true:

"items": {
    "item1": true,
    "item2": true,
    "item3": true,
    "item4": true,
    "item5": true,
    "item6": true
}

These items then need to show their corresponding images in order in a collectionview. Is there a way after adding these items to an array to get those itmes in the correct order?

This is the function I'm using now,it works but the order is different:

var appMenuJSON: NSDictionary?
var menuButtonsArray: [String?] = []

func getItems(){
    guard let items = appMenuJSON else {return}            
        for (key, value) in items {
            if let val = value as? Bool, val == true {
                menuButtonsArray.append(key as! String)
            }

}
SwiftyJD
  • 5,257
  • 7
  • 41
  • 92
  • Well there are some things that are not very clear in this question. First you say you have a JSON object but then in the code example it seems that this object is actually a NSDictionary? – Damiaan Dufaux Aug 07 '17 at 14:59
  • the json file is used as a guide for what should be showed in UI. If it's value is true, it's supposed to show. – SwiftyJD Aug 07 '17 at 15:01
  • If your problem has nothing to do with the data being in JSON format, then leave it out of the question. It will clarify the question. – Damiaan Dufaux Aug 07 '17 at 15:21

1 Answers1

3

Well once you decoded your JSON into a NSDictionary you have no way of getting the items back in the same order as they were in the JSON string.

So either sort the entries again using Array(items).sort (see Sort Dictionary by keys) or do a custom parsing of your JSON array to get the original ordering.

Damiaan Dufaux
  • 4,427
  • 1
  • 22
  • 33