tmsblgh
tmsblgh

Reputation: 527

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:

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? :)

(The sample is from: https://developer.apple.com/tutorials/swiftui/handling-user-input)

Upvotes: 0

Views: 2416

Answers (1)

Chip Jarred
Chip Jarred

Reputation: 2805

Store has a property that is an array of Category. I would guess that Category does not conform to Equatable or Hashable, and so Swift cannot synthesize conformance.

Landmark contains properties that all conform to Equatable and Hashable, so it can synthesize conformance for Landmark.

There are two solutions to make Store conform.

  1. Make Category conform to both protocols. Then Swift could synthesize conformance for Store.

  2. 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)

Depending on the implementation of Category, the simplest solution just might be:

extension Category: Hashable, Equatable { }

Upvotes: 4

Related Questions