gotnull
gotnull

Reputation: 27214

Binary operator '==' cannot be applied to two operands in if statement

Given the following struct:

struct Landmark {
    let id: String
    let name: String
    let location: CLLocationCoordinate2D
}

And the following @State:

@State var landmarks: [Landmark] = [
    Landmark(id: "1", name: "Sydney Harbour Bridge", location: .init(latitude: -33.852222, longitude: 151.210556)),
    Landmark(id: "2", name: "Brooklyn Bridge", location: .init(latitude: 40.706, longitude: -73.997))
]

private func selectNextLandmark() {
    if let selectedLandmark = selectedLandmark, let currentIndex = landmarks.firstIndex(where: { $0 == selectedLandmark }), currentIndex + 1 < landmarks.endIndex {
        self.selectedLandmark = landmarks[currentIndex + 1]
    } else {
        selectedLandmark = landmarks.first
    }
}

I'm getting the following error on the if line inside selectNextLandmark:

Operator function '==' requires that 'Landmark' conform to 'Equatable'

Is there a problem with my Landmark struct or is it a problem with the if statement syntax?

Upvotes: 2

Views: 2499

Answers (1)

Malik
Malik

Reputation: 3802

The message is quite clear

Operator function '==' requires that 'Landmark' conform to 'Equatable'

The struct Landmark must conform to Equatable protocol in order for it to know what equality means in reference to the Struct. Update your struct to

struct Landmark: Equatable {
    let id: String
    let name: String
    let location: CLLocationCoordinate2D

    static func == (lhs: Landmark, rhs: Landmark) -> Bool {
        //Your equating logic here
    }
}

Upvotes: 5

Related Questions