Trouble with KeyPathComparator and Bool (related: TableColumn)

Thou shalt not conform thy neighbor's type to thy neighbor's protocol. A Swift community term for this is retroactive conformance and it's bad idea—especially if the type and the protocol are part of the SDK (see the link).

Instead, define a BoolComparator:

struct BoolComparator: SortComparator {
    var order: SortOrder = .forward
    
    func compare(_ lhs: Bool, _ rhs: Bool) -> ComparisonResult {
        return order == .forward ? result(lhs, rhs) : result(rhs, lhs)
    }
    
    private func result(_ lhs: Bool, _ rhs: Bool) -> ComparisonResult {
        if !lhs && rhs { return .orderedAscending }
        if lhs && !rhs { return .orderedDescending }
        return .orderedSame
    }
}

And use it like this:

self.tempFiles.sort(
    using: KeyPathComparator(
        \ProcessFile.executableExists,
        comparator: BoolComparator()
    )
)
2 Likes