Swift 在堆栈中订阅词典
我正在尝试为堆栈中包含的字典下标,但每当我下标时,都会出现一个错误,如“无法为类型为Swift 在堆栈中订阅词典,swift,swift-subscript,Swift,Swift Subscript,我正在尝试为堆栈中包含的字典下标,但每当我下标时,都会出现一个错误,如“无法为类型为,[字典]”的值下标,索引类型为“UInt64”。 堆栈声明为: var cost : Stack<Dictionary<UInt64, UInt64>>? = nil 我试过用很多不同的方法来写,但它们都给出了相同的错误。 编辑:这是堆栈代码 struct Stack<T> { var items = [T]() mutating func push(_ i
,[字典]”的值下标,索引类型为“UInt64”。
堆栈声明为:
var cost : Stack<Dictionary<UInt64, UInt64>>? = nil
我试过用很多不同的方法来写,但它们都给出了相同的错误。
编辑:这是堆栈代码
struct Stack<T> {
var items = [T]()
mutating func push(_ item: T) {
items.append(item)
}
mutating func pop() -> T? {
return items.removeLast()
}
}
struct堆栈{
变量项=[T]()
变异函数推送(u项:T){
items.append(项目)
}
变异函数pop()->T{
return items.removeLast()
}
}
您声明了var items=[T]()
,因此items
是一个数组
,b
也是数组
。数组下标的类型是Int
,而不是UInt64
。请尝试以下操作:
if let b = x.cost?.items, let _ = b[Int(index)] {
项目不是可选的,所以我将其更改为
if(x.cost?.items[Int(index)]!=nil{
,并且成功了。非常感谢你,Rob。
if let b = x.cost?.items, let _ = b[Int(index)] {