AnySortComparator is a type erased implementation of the SortComparatorprotocol.
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 SortComparators:
let comparators: [SortComparator] // Not Valid!
Considering that the Sequence protocol offers a method for sorting with a Sequence of SortComparators, 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 AnySortComparators will be equal if their ‘base’ comparators have equal hashValues and their orders are the same. Or put another way:
AnySortComparator
AnySortComparatoris a type erased implementation of the SortComparatorprotocol.The Problem
SortComparatorhas anassociatedTypeand therefore cannot be used as a first class type.For example, it is not valid to create an array of
SortComparators:Considering that the
Sequenceprotocol offers a method for sorting with aSequenceofSortComparators, it would be nice to shake the constraint of only one concrete implementation ofSortComparator.The Solution
AnySortComparatorpreserves the behavior of the original compare function while still allowing mutation of the order.Hashable
The
hashValueof a givenAnySortComparatoris not equal to thehashValueof the ‘base’ comparator it holds. As expected, thehashValueof twoAnySortComparators will be equal if their ‘base’ comparators have equalhashValues and theirorders are the same. Or put another way: