0

I want to sort custom class based on specific key. so here I wrote a generic function:

extension Array where Element == [String : Any] {
    func sort(byKey key: String) -> [Element] {
        return sorted(by: { $0[key] < $1[key] })
    }
}

But it gives me error:

Binary operator '<' cannot be applied to two 'Any?' operands

Any help?

Update

Here is the model class, which I am using and sort based on different values.

//Added as per your suggestion.
extension ModelDirectoryInfo: Comparable {
    static func < (lhs: ModelDirectoryInfo, rhs: ModelDirectoryInfo) -> Bool {
        ///Error: Here again this is static
        //....
        return lhs.name < rhs.name
    }
}

struct ModelDirectoryInfo {

    let name: String
    let type: String
    let size: String
    let url: String
    let createDates: String
    let bytesize:String

    init(withDictionary dicValues: Dictionary<String, Any>) {
        self.name = dicValues["name"] as? String ?? ""
        self.type = dicValues["type"] as? String ?? ""
        self.size  = dicValues["size"] as? String ?? ""
        self.createDates = dicValues["createDate"] as? String ?? ""
        self.url = dicValues["url"] as? String ?? ""
        self.bytesize = dicValues["bytesize"] as? String ?? ""
    }
}
Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
  • @MartinR yes, value can be anything, but I can't think of key exists or not, can you suggest me something for ir? – Sohil R. Memon Feb 13 '19 at 08:37
  • @MartinR & Rakesh, you both are correct but the issue I am facing haven't faced by anyone till now? I am curious becaue `Generic` can be helpful. – Sohil R. Memon Feb 13 '19 at 08:45
  • 2
    The question changed considerably. Originally it was about sorting an array of dictionaries. Now it is about sorting an array of custom objects (which is answered e.g. here https://stackoverflow.com/q/46599074/1187415), but also (as it became apparent in the discussion) about accessing property values via *string.* – I have therefore deleted my answer. – Martin R Feb 13 '19 at 09:33

0 Answers0