Compare objects in Swift

I reviewed it many times and felt that I didn't really think about it, so I will write it as a memorandum.

Use Equatable

You can use Equtable to compare objects in Swift.

Purpose of use

For example, I think it is effective when you give two arguments to a structure and want to compare with only one argument.

sample

・ I want to judge a blue apple and a red apple as the same apple. ・ The information given is the name and color.

//Equatable ensures that objects can be compared
struct Fruit: Equatable {
    var name: String
    var color: String
    
    //When you want to get the result by judging only the name
    static func == (lhs: Fruit, rhs: Fruit) -> Bool {
        return lhs.name == rhs.name
    }
}

let gApple = Fruit(name: "Apple", color: "green")
let rApple = Fruit(name: "Apple", color: "red")

var result = gApple == rApple

print(result) // output: true

Summary

It's pretty rough, but I'd like to add it if there is a specific use.

Recommended Posts

Compare objects in Swift
Division becomes 0 in Swift
Compare Lists in Java
Multidimensional array in Swift
ARKit: Name objects in Reality Composer, get names in Swift
Photo library in Swift UI
Implement Swift UITextField in code
[Swift] I thought about compare
Compare Java 8 Optional with Swift
[Swift] Create UIButton class in code
Make an FPS counter in Swift
[React Native] Write Native Module in Swift
Create Master Detail in Swift UI
Specify multiple sort conditions in Swift
Handle C char ** well in Swift
Implementing side menus in Swift UI
Deleting AWS S3 Objects in Java
Time stamps in nanoseconds even in Swift!
Page Objects pattern in Appium java-client
(Limited to Java 7 or later) I want you to compare objects in Objects.equals
[swift5] How to specify color in hexadecimal
Customize View with View Modifier in Swift UI
Shorten the UUID to base64 in Swift.
HandleEvents closure not called in Swift Combine
What is Swift? Findings obtained in 3 weeks
Manage View status with enum in Swift
[GCD] Basics of parallel programming in Swift
Java-How to compare image files in binary
[Swift] How to fix Label in UIPickerView
Create an HTML/XML generator in Swift (dynamicMemberLookup)
Find an approximation of cosx in Swift
How to overwrite Firebase data in Swift
Hex and UIColor mutual conversion in Swift