connorvo
connorvo

Reputation: 821

Sort array of dictionaries where key is unknown

I have an array of dictionaries of type [[String:SchoolModel]]. The keys are the id of the school and then the school model contains info about the school like its name for example. I want to sort this array by SchoolModel.name, but can't figure out how since my key is a unique id for every element in the array.

struct SchoolModel {
   var name: String
   var city: String
   var state: String
}

Upvotes: 0

Views: 65

Answers (1)

Callam
Callam

Reputation: 11539

You can access the first value of each dictionary iterated to get the name.

struct SchoolModel {
    var name: String
    var city: String
    var state: String
}

let schools: [[String:SchoolModel]] = [
    ["1": SchoolModel(name: "1", city: "a", state: "x")],
    ["2": SchoolModel(name: "2", city: "b", state: "y")],
    ["3": SchoolModel(name: "3", city: "c", state: "z")]
]

print(schools.sorted {
    guard
        let a = $0.values.first?.name,
        let b = $1.values.first?.name else { return false }

    return a < b
})

However, you should consider adding an id property to your struct. You can make it optional so you can still initiate a SchoolModel that hasn't been created yet.

struct SchoolModel {
    var id: String?
    var name: String
    var city: String
    var state: String
}

Then where ever you are populating the array of dictionaries, append the SchoolModel object without embedding it inside a dictionary, resulting in an array of type [SchoolModel].

Upvotes: 1

Related Questions