Swift 中的有序地图 [英] Ordered map in Swift
问题描述
是否有任何内置方法可以在 Swift 2 中创建有序地图?数组 [T]
按对象附加到它的顺序排序,但字典 [K : V]
没有排序.
Is there any built-in way to create an ordered map in Swift 2? Arrays [T]
are sorted by the order that objects are appended to it, but dictionaries [K : V]
aren't ordered.
例如
var myArray: [String] = []
myArray.append("val1")
myArray.append("val2")
myArray.append("val3")
//will always print "val1, val2, val3"
print(myArray)
var myDictionary: [String : String] = [:]
myDictionary["key1"] = "val1"
myDictionary["key2"] = "val2"
myDictionary["key3"] = "val3"
//Will print "[key1: val1, key3: val3, key2: val2]"
//instead of "[key1: val1, key2: val2, key3: val3]"
print(myDictionary)
是否有任何内置方法可以创建以与数组相同的方式排序的有序 key : value
映射,还是我必须创建自己的类?
Are there any built-in ways to create an ordered key : value
map that is ordered in the same way that an array is, or will I have to create my own class?
如果可能,我想避免创建自己的类,因为 Swift 包含的任何内容很可能会更有效率.
I would like to avoid creating my own class if at all possible, because whatever is included by Swift would most likely be more efficient.
推荐答案
您可以使用 Int
类型的键来订购它们.
You can order them by having keys with type Int
.
var myDictionary: [Int: [String: String]]?
或
var myDictionary: [Int: (String, String)]?
我推荐第一种,因为它是一种更常见的格式(例如 JSON).
I recommend the first one since it is a more common format (JSON for example).
这篇关于Swift 中的有序地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!