在堆栈中订阅字典 swift

Subscripting a dictionary in a stack swift

我正在尝试下标包含在堆栈中的字典,但每当我这样做时,我都会收到类似“无法下标 '[Dictionary<UInt64, UInt 64>]' with an index of type 'UInt64'. 类型的值这样的错误 堆栈声明为:

var cost : Stack<Dictionary<UInt64, UInt64>>? = nil

给我带来麻烦的是:

if let b = x.cost?.items, let _ = b[index] {

我试过用多种不同的方式编写它,但它们都给出了相同的错误。 编辑:这是堆栈代码

struct Stack<T> {
    var items = [T]()
    mutating func push(_ item: T) {
        items.append(item)
    }
    mutating func pop() -> T? {
        return items.removeLast()
    }
}

您声明了 var items = [T](),因此 items 是一个 Array<T>,并且 b 也是 Array<T>。数组下标的类型是Int,不是UInt64。试试这个:

if let b = x.cost?.items, let _ = b[Int(index)] {