Custom comparison operator

thank you guys,

if i did so then i'd have to make all my types equatable even if they don't have to be.

class C {}

var c: C?
c <> nil // Operator function '<>' requires that 'C' conform to 'Equatable'

i also considered having isNil / isNonNil on Optional type to make nil checks more explicit.

this is the working solution i found:

infix operator <> : ComparisonPrecedence

extension Equatable {
static func <> (a: Self, b: Self) -> Bool {
return a != b
}
}

extension Optional {
static func <> (a: Wrapped?, b: _OptionalNilComparisonType) -> Bool {
return a != b
}

static func <> (a: _OptionalNilComparisonType, b: Wrapped?) -> Bool {
return a != b
}
}

extension BinaryInteger {
static func <> (a: Self, b: Other) -> Bool where Other : BinaryInteger {
return a != b
}
}

don't ask what _OptionalNilComparisonType is... i just copied/pasted it from a similar "func !=" of Optional type.

the int functions were needed as otherwise Int(0) <> Int32(0) complained (and it works with the != version)

so tuples are not Equatable even if we can compare them? weird.

this is very unfortunate and not scalable. but in reality in my code base i've encountered only two instances of such tuple types that i compared with !=, so i just changed the comparison to ~(a == b) (~ - is my analog of !)

given these changes now the only instances of ! in my code base are those associated with something unsafe (be it optional unwrap or implicit optionals or unsafe type cast)

1 Like