lets say we have a custom class named imageFile and this class contains two properties.
class imageFile {
var fileName = String()
var fileID = Int(
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.