AnySortComparator

AnySortComparator
is a type erased implementation of the SortComparator protocol
.
The Problem
SortComparator
has an associatedType
and therefore cannot be used as a first class type.
For example, it is not valid to create an array of SortComparator
s:
let comparators: [SortComparator] // Not Valid!
Considering that the Sequence
protocol offers a method for sorting with a Sequence
of SortComparator
s, it would be nice to shake the constraint of only one concrete implementation of SortComparator
.
The Solution
AnySortComparator
preserves the behavior of the original compare function while still allowing mutation of the order.
Hashable
The hashValue
of a given AnySortComparator
is not equal to the hashValue
of the ‘base’ comparator it holds. As expected, the hashValue
of two AnySortComparator
s will be equal if their ‘base’ comparators have equal hashValue
s and their order
s are the same. Or put another way:
AnySortComparator(KeyValueComparator(\Int.self)).hashValue != KeyValueComparator(\Int.self).hashValue
AnySortComparator(KeyValueComparator(\Int.self)).hashValue == AnySortComparator(KeyValueComparator(\Int.self)).hashValue
AnySortComparator
AnySortComparator
is a type erased implementation of the SortComparatorprotocol
.The Problem
SortComparator
has anassociatedType
and therefore cannot be used as a first class type.For example, it is not valid to create an array of
SortComparator
s:Considering that the
Sequence
protocol offers a method for sorting with aSequence
ofSortComparator
s, it would be nice to shake the constraint of only one concrete implementation ofSortComparator
.The Solution
AnySortComparator
preserves the behavior of the original compare function while still allowing mutation of the order.Hashable
The
hashValue
of a givenAnySortComparator
is not equal to thehashValue
of the ‘base’ comparator it holds. As expected, thehashValue
of twoAnySortComparator
s will be equal if their ‘base’ comparators have equalhashValue
s and theirorder
s are the same. Or put another way: