包含 Int 数组的字典——获取键和索引的值
Dictionary containing Int array – getting value for key and index
我想创建一个字典,将 Int
映射到 Int
数组。当我向它添加值时,使用结构 var myDictionary = [Int:[Int]]()
似乎工作正常。但是我在检索键和索引的值时遇到问题。我正在做 myDictionary[key][index]
,但它似乎不起作用。我收到错误
Cannot subscript a value of type '[(Int)]?' with an index of type 'Int'
你能解释一下我做错了什么吗?
如果您使用键为 Dictionary
下标,您会得到一个可选值(在本例中为 [Int]?
)。如果你想下标这个数组你必须使用可选链接因为可选没有这个下标:
let optionalElement: Int? = myDictionary[key]?[index]
我想创建一个字典,将 Int
映射到 Int
数组。当我向它添加值时,使用结构 var myDictionary = [Int:[Int]]()
似乎工作正常。但是我在检索键和索引的值时遇到问题。我正在做 myDictionary[key][index]
,但它似乎不起作用。我收到错误
Cannot subscript a value of type '[(Int)]?' with an index of type 'Int'
你能解释一下我做错了什么吗?
如果您使用键为 Dictionary
下标,您会得到一个可选值(在本例中为 [Int]?
)。如果你想下标这个数组你必须使用可选链接因为可选没有这个下标:
let optionalElement: Int? = myDictionary[key]?[index]