I have a number of structs which all have a common 'order' property, and I want to make a protocol to avoid repeating the func < implementation everywhere.
Unfortunately, the obvious thing doesn't work:
protocol Orderable: Comparable {
var order: Int { get }
}
extension Orderable {
static func < (lhs: any Orderable, rhs: any Orderable) -> Bool {
return lhs.order < rhs.order
}
}
struct Item: Decodable, Orderable {
let name: String
let order: Int
}
This one might work if you expect that the lhs and rhs might be different types.
Some sideways advice is that an Array<any Orderable> can sometimes be looked at from a different POV. Instead of a hetergenous collection of struct elements… could you build a homogenous collection of AGT enum elements?