[英]Swift - struct type does not conform to protocol
I am learning Swift, but I am bit stuck with the basics.. Downloaded a sample project from Apple but still not see what is the difference between these two:我正在学习 Swift,但我有点坚持基础知识.. 从 Apple 下载了一个示例项目,但仍然看不出这两者之间有什么区别:
My struct:我的结构:
import Foundation
import SwiftUI
import CoreLocation
struct Store: Hashable, Codable, Identifiable {
var id: Int
var name: String
var categories: [Category]
private var logoName: String
var logo: Image {
Image(logoName)
}
private var coordinates: Coordinates
var locationCoordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(
latitude: coordinates.latitude,
longitude: coordinates.longitude)
}
struct Coordinates: Hashable, Codable {
var latitude: Double
var longitude: Double
}
}
Sample:样本:
import Foundation
import SwiftUI
import CoreLocation
struct Landmark: Hashable, Codable, Identifiable {
var id: Int
var name: String
var park: String
var state: String
var description: String
var isFavorite: Bool
private var imageName: String
var image: Image {
Image(imageName)
}
private var coordinates: Coordinates
var locationCoordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(
latitude: coordinates.latitude,
longitude: coordinates.longitude)
}
struct Coordinates: Hashable, Codable {
var latitude: Double
var longitude: Double
}
}
The first is failing with:第一个是失败的:
"Type 'Store' does not conform to protocol 'Equatable'"
"Type 'Store' does not conform to protocol 'Hashable'"
The second one is working properly.第二个工作正常。
What is the difference?有什么区别? Is there a settings somewhere in Xcode?
Xcode 中是否有设置? :)
:)
(The sample is from: https://developer.apple.com/tutorials/swiftui/handling-user-input ) (样本来自: https://developer.apple.com/tutorials/swiftui/handling-user-input )
Store
has a property that is an array of Category
. Store
有一个属性,它是Category
的数组。 I would guess that Category
does not conform to Equatable
or Hashable
, and so Swift cannot synthesize conformance.我猜
Category
不符合Equatable
或Hashable
,因此 Swift 无法综合一致性。
Landmark
contains properties that all conform to Equatable
and Hashable
, so it can synthesize conformance for Landmark
. Landmark
包含所有符合Equatable
和Hashable
的属性,因此它可以综合符合Landmark
。
There are two solutions to make Store
conform.有两种解决方案可以使
Store
符合要求。
Make Category
conform to both protocols.使
Category
符合这两种协议。 Then Swift could synthesize conformance for Store
.然后 Swift 可以合成
Store
的一致性。
Explicitly implement the conformance for Hashable
and Equatable
for Store
by implementing static func == (lhs: Store, rhs: Store) -> Bool
and func hash(into: inout Hasher)
通过实现
static func == (lhs: Store, rhs: Store) -> Bool
and func hash(into: inout Hasher)
显式实现Hashable
和Equatable
for Store
的一致性
Depending on the implementation of Category
, the simplest solution just might be:根据
Category
的实现,最简单的解决方案可能是:
extension Category: Hashable, Equatable { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.