gpt4 book ai didi

swift - 二元运算符 '==' 不能应用于 if 语句中的两个操作数

转载 作者:行者123 更新时间:2023-11-28 10:27:21 24 4
gpt4 key购买 nike

给定以下结构:

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

以及以下@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
}
}

我在 selectNextLandmark 内的 if 行收到以下错误:

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

我的 Landmark struct 是否有问题,或者 if 语句语法有问题吗?

最佳答案

信息很明确

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

结构体Landmark必须符合Equatable协议(protocol),以便它知道相对于结构体的相等性意味着什么。将您的结构更新为

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

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

关于swift - 二元运算符 '==' 不能应用于 if 语句中的两个操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58279589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com