The introduction

When we want to compare the equality of custom class values in Swift, we need to implement the Equatable protocol

The protocol only has the following method

static func == (lhs: Self, rhs: Self) -> Bool

I just need to compare the values of the properties to be equal, but I noticed that we didn’t deal with the Optional case, didn’t we deal with the parameters of the function? It looks like the code works fine with Optional

So what happens when the parameter is Optional?

explore

I did a search on the Internet and found that someone else was wondering the same thing. He ran some tests and found that Optional was right, so forget it.

It just works!

That makes it even more confusing, but swift is open source, so we can find out how Swift does it.

And then I saw this code in Option. swift, which handled the Optional situation for us.

extension Optional : Equatable where Wrapped : Equatable {

  @inlinable
  public static func= =(lhs: Wrapped? , rhs: Wrapped?) -> Bool {
    switch (lhs, rhs) {
    case let(l? , r?) :return l == r
    case (nil.nil) :return true
    default:
      return false}}}Copy the code

In other words, if LHS and RHS are not nil, then we’ll do it the way we implemented it; If both are nil, then return true;

The rest of the cases return false.

The resources

Optional.swift

swift-equatable-with-optionals