斯威夫特的有序字典 [英] Ordered dictionary in Swift
问题描述
是否有任何内置方式在Swift 2中创建有序地图?数组 [T]
按照附加对象的顺序排序,但字典 [K:V]
aren
例如
var myArray:[String ] = []
myArray.append(val1)
myArray.append(val2)
myArray.append(val3)
//将始终打印val1,val2,val3
print(myArray)
var myDictionary:[String:String] = [:]
myDictionary [key1 ] =val1
myDictionary [key2] =val2
myDictionary [key3] =val3
//将打印[key1: val1,key3:val3,key2:val2]
//而不是[key1:val1,key2:val2,key3:val3]
print(myDictionary)
有没有内置的方法来创建一个订购的键:value
map是以与数组相同的方式进行排序,还是必须创建自己的类?
如果可能,我想避免创建自己的课程,因为Swift包含的任何内容最有可能更有效。
您可以通过键入类型为 Int
的订单。
var myDictionary:[Int:[String:String]]?
或
var myDictionary:[Int:(String,String)]?
我推荐第一个,因为它是一个更常见的格式(例如JSON)。 >
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.
For example
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)
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?
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.
You can order them by having keys with type Int
.
var myDictionary: [Int: [String: String]]?
or
var myDictionary: [Int: (String, String)]?
I recommend the first one since it is a more common format (JSON for example).
这篇关于斯威夫特的有序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!