首页 > 解决方案 > Xcode 不提供添加协议存根

问题描述

我正在尝试使我的 struct Card 符合 Hashable 协议(用于字典),但由于某种原因,Xcode 不会以红色错误对我大喊大叫,例如“Type 'Card' 不符合协议 'Hashable'。我不明白为什么。我希望 Xcode 添加协议存根。

import Foundation

struct Card : Hashable {
    
    var isFaceUp = false
    var isMatched = false
    var identifier : Int
    
    private static var identifierFactory = 0
    
    private static func getUniqueIdentifier() -> Int {
        Card.identifierFactory += 1
        return Card.identifierFactory
    }
    
    init() {
        identifier = Card.getUniqueIdentifier()
    }
}

标签: iosswiftxcode

解决方案


它没有显示任何错误,说明您需要添加协议存根以符合它,因为该Hashable协议是在 struct 上自动合成的Card。因此,添加Hashable协议一致性不需要任何额外的代码。

如果由于某种原因您想要覆盖默认实现,您可以通过执行以下操作来实现。

struct Card: Hashable {
    //...
    func hash(into hasher: inout Hasher) {
        hasher.combine(identifier) // combine any hashable you like
    }
}

推荐阅读