BallpointBen
BallpointBen

Reputation: 13750

Does Swift support automatic generation of operators?

I'm looking to avoid writing unnecessary code. If I define == and < for a type, is it possible to automatically obtain <= (< or ==), > (not < and not ==), or >= (not <)? I would think Swift would provide these operators for free, but that doesn't seem to be the case.

Upvotes: 0

Views: 53

Answers (3)

Code Different
Code Different

Reputation: 93161

Yes. That's exactly how Comparable protocol works. You only have to define 2 operators: < and ==. Swift will figure out the rest.

struct MyStruct : Comparable {
    var value: Int
}

func == (lhs: MyStruct, rhs: MyStruct) -> Bool {
    return lhs.value == rhs.value
}

func < (lhs: MyStruct, rhs: MyStruct) -> Bool {
    return lhs.value < rhs.value
}

let a = MyStruct(value: 1)
let b = MyStruct(value: 42)

print(b > a) // We never defined `>` operator

Upvotes: 1

L&#233;o Natan
L&#233;o Natan

Reputation: 57050

Yes.

Implement == from Equatable and < from Comparable, and the rest of the operators will use the default implementations as you expect.

To add Comparable conformance to your custom types, define the < and == operators as static methods of your types. The == operator is a requirement of the Equatable protocol, which Comparable extends—see that protocol’s documentation for more information about equality in Swift. Because default implementations of the remainder of the relational operators are provided by the standard library, you’ll be able to use !=, >, <=, and >= with instances of your type without any further code.

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385610

If you make your type conform to Equatable, it will provide a default implementation of != based on your ==.

If you make your type conform to Comparable, it will provide default implementations of >, <=, and >= based on your <.

Note that Comparable extends Equatable, so you must also provide == to conform to Comparable.

Upvotes: 1

Related Questions