Bigair
Bigair

Reputation: 1592

How to check equality by field on swift objects

How to check if two swift objects has save values for all the field?

I want to do this with as little effort as possible. I would not like to implement equatable for every object to manually implement equality check.

NOTE: I am not checking equality for ID but checking if all the fields have equal values.


struct Post {
    let id: Int
    let owner: User
    let comment: String
}

struct User {
    let id: Int
    let name: String
}

let user = User(id: 1, name: "Steve")
let post = Post(id: 1, owner: user, comment: "I invented iPhone")

let user2 = User(id: 1, name: "Steve")
let post2 = Post(id: 1, owner: user2, comment: "I invented iPhone")


if post == post2 {
    print("equal") // Should reach here
} else {
    print("not equal")
}

Upvotes: 1

Views: 450

Answers (1)

Frankenstein
Frankenstein

Reputation: 16341

Make Post and User conform to Equatable protocol.

struct Post: Equatable {
    let id: Int
    let owner: User
    let comment: String
}

struct User: Equatable {
    let id: Int
    let name: String
}

If you want custom conformance, for example you don't want to check for the equality of parameter comment then use:

struct Post: Equatable {
    static func == (lhs: Post, rhs: Post) -> Bool { lhs.id == rhs.id } // could add "&& lhs.owner.id == rhs.owner.id" if that's what you're going for
}

And then:

let user = User(id: 1, name: "Steve")
let post = Post(id: 1, owner: user, comment: "I invented iPhone")

let user2 = User(id: 1, name: "Steve")
let post2 = Post(id: 1, owner: user2, comment: "I invented iPhone")


if post == post2 {
    print("equal") // reaches here
} else {
    print("not equal")
}

Upvotes: 1

Related Questions