I know JSON keys don't have any order and can be generated randomly, but there isn't anything preventing me from writing this function and from my tests this works on my every use case I tested.
func ==<T: Encodable> (lhs: T, rhs: T) -> Bool {
let encoder = JSONEncoder()
do {
let leftEncoded = try encoder.encode(lhs)
let rightEncoded = try encoder.encode(rhs)
return leftEncoded == rightEncoded
} catch {
return false
}
}
The problem I want to solve is writing a function for a type which has an array of one protocol with like 20 different implementation, which I have to implement the ==
function instead of swift auto synthesise. And I know I can switch to JSONSerialization.writeJSONObject
with option .sortedKeys
to persist the keys order.
What is the downside of this implementation instead of any other method of writing ==
function?