Generic function to sort array of class or struct by properties in Swift

Here you go:

extension Array {
    mutating func propertySort<T: Comparable>(_ property: (Element) -> T) {
        sort(by: { property($0) < property($1) })
    }
}

Usage:

persons.propertySort({$0.name})

And here is a non-mutating version:

func propertySorted<T: Comparable>(_ property: (Element) -> T) -> [Element] {
    return sorted(by: {property($0) < property($1)})
}

As Leo Dabus pointed out, you can generalise the extension to any MutableCollection that is also a RandomAccessCollection:

extension MutableCollection where Self : RandomAccessCollection {
    ...

Leave a Comment