在 Swift 中,我如何在协议中添加 where 约束是等同的?

问题描述 投票:0回答:1

我想写一个通用的

deck
卡类,我可以在不同的应用程序中使用它,它目前有一个协议,但我无法向协议添加
where Element : Equatable
,因为它抱怨说:

实例方法要求'find'不能添加约束 'Self.Element: Equatable' on 'Self'

我尝试添加时在线上抛出此错误:

func find(_ card: Element) -> Int? where Element: Equatable

协议。

Swift代码如下,

protocol DeckDelegate: AnyObject {
    associatedtype Element
    var size: Int { get }
    var isEmpty: Bool { get }
    var cards:[Element] { get set }
    func push(_ element: Element)
    func pop() -> Element?
    func find(_ card: Element) -> Int? where Element: Equatable
}

class Deck<Element> {
    func find(_ card: Element) -> Int? where Element : Equatable {
        return cards.firstIndex(of: card)
    }
    
    var size: Int {
        return cards.count
    }
    var isEmpty: Bool {
        return (cards.count == 0)
    }
    
    internal var cards: [Element] = []
    
    func push(_ element: Element) {
        cards.append(element)
    }
    
    func pop() -> Element? {
        // TBD
    }
    
}

我的问题是,如何将约束添加到 Swift 协议中?

谢谢。

swift generics swift-protocols
1个回答
0
投票

如果我理解正确的话,你想要一个

find
函数可用仅当
Element
Equatble
,但你不想在函数签名本身中引入一个新的泛型类型。所以你需要扩展协议:

extension DeckDelegate where Element: Equatable {
    func find(_ card: Element) -> Int? where Element: Equatable {
        cards.firstIndex(of: card)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.