[swift-evolution] sortBy, minElementBy and maxElementBy methods

David Owens II david at owensd.io
Thu Dec 31 10:45:23 CST 2015


I don’t get the resistance to Dave’s solution? I think it works well and much more applicable. Taking Susan’s original example, it’s not uncommon to want to sort or filter by multiple mechanisms.


func byComparing<T, U: Comparable>(getComparisonKey: (T)->U) -> (T, T) -> Bool {
    return { getComparisonKey($0) < getComparisonKey($1) }
}

struct Person {
    var name: String
    var age: Int
    var height: Int
}

let peoples = [
    Person(name: "Hawk", age: 24, height: 60),
    Person(name: "Andrew", age: 23, height: 66)
]

let youngest = peoples.minElement(byComparing { $0.age })
let tallest = peoples.maxElement(byComparing { $0.height })

print("youngest: \(youngest?.name ?? "<none>")")
print("tallest: \(tallest?.name ?? "<none>")")


-David

> On Dec 31, 2015, at 8:19 AM, Dave Abrahams via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On Dec 31, 2015, at 4:14 AM, Tino Heth <2th at gmx.de <mailto:2th at gmx.de>> wrote:
>> 
>> 
>>> func byComparing<T, U: Comparable>(getComparisonKey: (T)->U) -> (T, T) -> Bool {
>>>   return { getComparisonKey($0) < getComparisonKey($1) }
>>> }
>> I've written something similar to bring file URLs into the order of their creation dates.
>> It is a small extension for collection types, and its only downside will disappear as soon as properties are accessible via method calls (afair there is a proposal in the making).
>> 
>> It was quite a lot fiddling with generics, and I don't have the tiny piece of code on my own computer, but it works in a way that you can do
>> let sorted = array.sortUsingAccessor(ElementType.methodThatReturnsComparable)
>> Beside the problems with properties, I really liked that approach.
> 
> This seems to be essentially the same design as Susan’s, and has the same problem: it requires a new overload for every algorithm that takes a comparison predicate.
> 
> -Dave
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151231/bf40891a/attachment.html>


More information about the swift-evolution mailing list