对会员的含糊不清的提及'包含'

时间:2018-04-08 15:54:20

标签: swift struct collections swift4

我已经为Stack定义了一个结构:

struct Stack<T> {
    private(set) var elements = [T]()
    var isEmpty: Bool { return elements.isEmpty }

    mutating func push(newElement: T) {
        elements.append(newElement)
    }

    mutating func pop() -> T {
        return elements.removeLast()
    }

    func top() -> T? {
        return elements.last
    }
}

当我使用该方法获取最后一个元素并检查它是否在集合中时:

if operators.contains(stack.top()!) {
//do smth
}

编译器引发错误:&#34;对成员的模糊引用&#39;包含&#39;&#34;

更新:该集合定义为:

struct Operator: OperatorType {
    let name: String
    let precedence: Int
    let associativity: Associativity
    // same operator names are not allowed
    var hashValue: Int { return "\(name)".hashValue }

    init(_ name: String, _ precedence: Int, _ associativity: Associativity) {
        self.name = name; self.precedence = precedence; self.associativity = associativity
    }
}

和init:

let operators: Set <Operator> = [
    Operator("%", 4, .Right),
    Operator("*", 3, .Left),
    Operator("/", 3, .Left),
    Operator("+", 2, .Left),
    Operator("-", 2, .Left)
]

我做错了什么?

1 个答案:

答案 0 :(得分:2)

这是因为您要查找的contains方法仅存在于Array.Element : Equatable

的位置
  

取自stdlib

extension Array where Element : Equatable {

     ...

     public func contains(_ element: Element) -> Bool
}

假设someCollectionArray<Stack>,那么您需要将Stack更改为:

struct Stack<T: Equatable> : Equatable {

使用Swift 4.1自动处理Equatable一致性。 Source