如何在Swift iOS中顺序访问Dictionary项目? [英] How to access Dictionary items sequentially in Swift iOS?
问题描述
是否可以按顺序访问字典中的项目。我知道字典主要用于随机访问。当我尝试访问作为键值对时,我的订单更改为名称,id,标题等...
Is it possible to access the items sequentially on the dictionary. I know that dictionary mainly intended for random access. When I am trying to access as key value pairs, my order changes to name, id, header,...etc
let inputDataSet = ["id":1, "name":"Thomas", "role":"Programming Geek", "header":"bla", "dept":"nloo", "address":"dsd", "pic":"asd"
for (key,value) in inputDataSet {
print("current key:\(key) value:\(value as! String)")
}
推荐答案
最适合您的选择这将是 KeyValuePairs
The best option for you here would be KeyValuePairs
键值对的轻量级集合。
A lightweight collection of key-value pairs.
当您需要有序键值对集合并且不需要快速键查找时
when you need an ordered collection of key-value pairs and don’t require the fast key lookup
let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,
"Evelyn Ashford": 10.76,
"Evelyn Ashford": 10.79,
"Marlies Gohr": 10.81]
print(recordTimes.first!)
// Prints "("Florence Griffith-Joyner", 10.49)"
引用: KeyValuePairs
但是,如果您想以其他方式解决它,我建议使用 Array
。要获取键值,可以将其存储在 Tuple
中。假设数组元组。请看下面的示例:
However, If you want to solve it different way I would recommend Array
. To have a key, value in collection you can store it in Tuple
. Let say array of tuples. Take a look on example below:
let inputDataSet: [(String, Any)] = [("id",1), ("name","Thomas"), ("role","Programming Geek"), ("header","bla"), ("dept","nloo"), ("address","dsd"), ("pic","asd")]
for (key, value) in inputDataSet {
print("current key:\(key) value:\(value)")
}
上面的狙击结果如下所示:
Result of the sniper above is as presented below:
current key:id value:1
current key:name value:Thomas
current key:role value:Programming Geek
current key:header value:bla
current key:dept value:nloo
current key:address value:dsd
current key:pic value:asd
为此,您有了订单和键值对象。
希望对您有所帮助!
Thanks to this you have an order and key, value object. Hope it helps!
更新:
答案已更新以反映更改。
Answer was updated to reflect changes.
将DictionaryLiteral类型重命名为KeyValuePairs
这篇关于如何在Swift iOS中顺序访问Dictionary项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!