繁体   English   中英

Swift - 结构类型不符合协议

[英]Swift - struct type does not conform to protocol

我正在学习 Swift,但我有点坚持基础知识.. 从 Apple 下载了一个示例项目,但仍然看不出这两者之间有什么区别:

我的结构:

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
    }
}

样本:

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
    }
}

第一个是失败的:

"Type 'Store' does not conform to protocol 'Equatable'"
"Type 'Store' does not conform to protocol 'Hashable'"

第二个工作正常。

有什么区别? Xcode 中是否有设置? :)

(样本来自: https://developer.apple.com/tutorials/swiftui/handling-user-input

Store有一个属性,它是Category的数组。 我猜Category不符合EquatableHashable ,因此 Swift 无法综合一致性。

Landmark包含所有符合EquatableHashable的属性,因此它可以综合符合Landmark

有两种解决方案可以使Store符合要求。

  1. 使Category符合这两种协议。 然后 Swift 可以合成Store的一致性。

  2. 通过实现static func == (lhs: Store, rhs: Store) -> Bool and func hash(into: inout Hasher)显式实现HashableEquatable for Store的一致性

根据Category的实现,最简单的解决方案可能是:

extension Category: Hashable, Equatable { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM