Complete guide on custom class/struct comparison

Needone App
2 min readAug 15, 2020

--

In Swift, you can either use class or struct to define your custom class. Most likely in the later development, you would need to have an array of such custom modelsomewhere in the project, and each of the custom model in the array are unique, in other words, you want an array/dictionary/set only includes non-duplicated custom model objects. So the following are the complete guide of some examples showing how to do compare your own custom model:

In Swift, you can either use class or struct to define your custom class. Here are some examples.

Struct Model

Custom Struct

In the case above, we are assuming if two notes have different username, latitude, longitude and text, they are two different notes, so if you want to make two of above objects can be comparable, add the following code:

Custom struct

Class Model

Sometimes we are using class for the model, see the following code for the same functionality:

Custom class

Class Model inherited from NSObject

Sometimes we have the special requirements that model class must inherited from NSObject, so you have to override the isEqual. See the following code for the same functionality:

Custom class

Why do we need to override?

With overriding isEqual or ==, you can make use a lot of inner-built methods such as contains, filter etc, an example of showing contains:

Conclusion

  • Custom Struct/Class: need to extend Equatable and override the operand ==.
  • Custom Class inherited from NSObject: need to override isEqual.

--

--

No responses yet