如何将字典转换为数组 [英] How to convert dictionary to array
本文介绍了如何将字典转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望将字典转换为数组,方法是将字典中的每个 [String:Int]
显示为数组中的字符串。
I want to convert my dictionary to an array, by showing each [String : Int]
of the dictionary as a string in the array.
例如:
var myDict: [String : Int] = ["attack" : 1, "defend" : 5, "block" : 12]
我知道 myDict.keys.array
和 myDict.values.array
,但我希望他们能够展示一起在阵列中。这就是我的意思:
I'm aware of myDict.keys.array
and myDict.values.array
, but I want them to show up in an array together. Here's what I mean:
var myDictConvertedToArray = ["attack 1", "defend 5", "block 12"]
提前致谢。
推荐答案
这将有效:
var myDict:[String : Int] = ["attack" : 1, "defend" : 5, "block" : 12]
var arr = [String]()
for (key, value) in myDict {
arr.append("\(key) \(value)")
}
请注意,词典无序,因此您的数组的顺序可能与您预期的不同。
Note that dictionaries are unordered, so the order of your array might not be what you expect.
在 Swift中2.0 ,这也可以用 map
完成:
let arr = myDict.map {"\($0) \($1)"}
这篇关于如何将字典转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文