Search code examples
arraysswiftdictionaryexc-bad-access

Appending dictionary values to array in Swift


I have a dictionary of type [String: Object], where MyObject is an array of AnotherObject. I need to have it sorted as I need to fill an UITableView with Keys.countnumber of sections and Object.count number of rows in each section. I put all the keys in an array, but when I try to append the values into another array I get Thread 1: EXC_BAD_ACCESS (code=1, address=0x8).

This is the code I'm using

var dictionary = [String: MyObject]()
var sortedKeys: [String]?
var sortedValues = [MyObject]()



func sortItems() {

        self.sortedKeys = self.dictionary.keys.sorted(by: >)

        let sortedDict = self.dictionary.sorted(by: {$0.key > $1.key})
        for (_, value) in sortedDict {
            print(value)
            self.sortedValues.append(value)
        }

    }

In the for loop, when I don't try to append the values to the array, it prints all the sorted values, the problem comes when I want to have them in an Array.

Edit

The dictionary is like this:

struct Object: Decodable {
    let elements: [AnotherObject]
}

struct AnotherObject: Decodable {
    let time, Id, Status: Int?
    let date, startTime, endTime: String?
}

dictionary: [String: Object]

So the keys are numbers (representing days) and every day has an Object with (at least) one anotherObject. I get the JSON from the API.

Thanks in advance


Solution

  • You should only sort the keys and then use that array to select from the dictionary and append your sortedValues array. I made the sortedKeys into a local variable

    func sortItems() {
        let sortedKeys = self.dictionary.keys.sorted(by: >)
    
        for key in sortedKeys {
            if let obj = dictionary[key] {
                self.sortedValues.append(obj)
            }
        }
    }
    

    I don't know if this will make a difference in regard to the crash but another way is to let the function return an array

    func sortItems() -> [Object] {
        let sortedKeys = self.dictionary.keys.sorted(by: >)
        var result: [Object]()
    
        for key in sortedKeys {
            if let obj = dictionary[key] {
                result.append(obj)
            }
        }
        return result
    }
    

    and then call it

    self.sortedValues = sortItems()