Swift how to sort array of custom objects by property value

前端 未结 18 2178
逝去的感伤
逝去的感伤 2020-11-22 02:12

lets say we have a custom class named imageFile and this class contains two properties.

class imageFile  {
    var fileName = String()
    var fileID = Int(         


        
18条回答
  •  梦谈多话
    2020-11-22 02:43

    Sort using KeyPath

    you can sort by KeyPath like this:

    myArray.sorted(by: \.fileName, <) /* using `<` for ascending sorting */
    

    By implementing this little helpful extension.

    extension Collection{
        func sorted(
            by keyPath: KeyPath,
            _ comparator: (_ lhs: Value, _ rhs: Value) -> Bool) -> [Element] {
            sorted { comparator($0[keyPath: keyPath], $1[keyPath: keyPath]) }
        }
    }
    

    Hope Swift add this in the near future in the core of the language.

提交回复
热议问题