我这样做是为了遍历我的字典,直到我匹配密钥。我的字典被定义为[Int:String]
var index = 0
for (key, value) in mylist! {
if key == property.propertyValue as! Int {
// use index here
}
index += 1
}
有更好的方法吗?我看到了过滤的例子(类似下面的例子),但我不知道如何使它与字典一起工作。我可以使用这样的东西来找到项目的索引吗?或者还有另一种方式吗?
mylist.filter{$0.key == 1}
更新 这有效:
let index = Array(mylist!.keys).index(of: 1)
但这并不是:
let index = mylist!.index(forKey: 1)
看来他们俩都应该工作。我想知道为什么第二个没有。
答案 0 :(得分:6)
字典是无序集合类型,没有索引。
您可以通过键
直接获取值let value = mylist[property.propertyValue as! Int]
答案 1 :(得分:2)
如果我理解正确,你可以这样做:
let myList = [
2: "Hello",
4: "Goodbye",
8: "Whats up",
16: "Hey"
]
let index = Array(myList.keys).index(of: property.propertyValue)
然后再找到你要找的钥匙......
let key = Array(myList.keys)[index!]
正如其他答案中所说,字典可能不是您正在寻找的数据结构。但这应该回答你提出的问题。
答案 2 :(得分:0)
鉴于你的字典
let dict = [1:"a", 2:"b", 3: ""]
你可以简单地提取给定键的索引(例如`1)
let indexForKey1 = dict.index(forKey: 1)
您还可以构建一个字典,其中键是索引,值是dict的键
let indexes = dict.keys.map { dict.index(forKey: $0) }
顺便说一句:你真的需要做什么?