ios Swift 中的有序地图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30969688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ordered map in Swift
提问by Jojodmo
Is there any built-inway 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.
是否有任何内置方法可以在 Swift 2 中创建有序地图?数组[T]
按对象附加到它的顺序排序,但字典[K : V]
没有排序。
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?
是否有任何内置方法可以创建以key : value
与数组相同的方式排序的有序映射,还是我必须创建自己的类?
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.
如果可能的话,我想避免创建自己的类,因为 Swift 包含的任何内容很可能会更有效率。
采纳答案by chrisamanse
You can order them by having keys with type Int
.
您可以通过使用 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).
我推荐第一种,因为它是一种更常见的格式(例如 JSON)。
回答by Mundi
Just use an array of tuples instead. Sort by whatever you like. All "built-in".
只需使用一组元组。按你喜欢的排序。全部“内置”。
var array = [(name: String, value: String)]()
// add elements
array.sort() { let pairs: KeyValuePairs = ["john": 1,"ben": 2,"bob": 3,"hans": 4]
print(pairs.first!)
.name < .name }
// or
array.sort() { let sortedDictionary = unsortedDictionary.sorted() { var orderedDictionary = [(key:String, value:String)]()
.key > .key }
.0 < .0 }
回答by coffeecoder
"If you need an ordered collection of key-value pairs and don't need the fast key lookup that Dictionary provides, see the DictionaryLiteraltype for an alternative." - https://developer.apple.com/reference/swift/dictionary
“如果您需要键值对的有序集合并且不需要 Dictionary 提供的快速键查找,请参阅DictionaryLiteral类型以获取替代方法。” - https://developer.apple.com/reference/swift/dictionary
回答by Duncan C
As Matt says, dictionaries (and sets) are unordered collections in Swift (and in Objective-C). This is by design.
正如 Matt 所说,字典(和集合)是 Swift(和 Objective-C)中的无序集合。这是设计使然。
If you want you can create an array of your dictionary's keys and sort that into any order you want, and then use it to fetch items from your dictionary.
如果需要,您可以创建一个字典键数组并将其排序为您想要的任何顺序,然后使用它从字典中获取项目。
NSDictionary
has a method allKeys that gives you all the keys of your dictionary in an array. I seem to remember something similar for Swift Dictionary objects, but I'm not sure. I'm still learning the nuances of Swift.
NSDictionary
有一个方法 allKeys 可以在数组中为您提供字典的所有键。我似乎记得 Swift Dictionary 对象的类似内容,但我不确定。我仍在学习 Swift 的细微差别。
EDIT:
编辑:
For Swift Dictionaries it's someDictionary.keys
对于 Swift Dictionaries,它是 someDictionary.keys
回答by barola_mes
You can use KeyValuePairs
,
from documentation:
您可以使用KeyValuePairs
,来自文档:
Use a KeyValuePairs instance when you need an ordered collection of key-value pairs and don't require the fast key lookup that the Dictionary type provides.
##代码##当您需要键值对的有序集合并且不需要 Dictionary 类型提供的快速键查找时,请使用 KeyValuePairs 实例。
//prints (key: "john", value: 1)
//打印(键:“约翰”,值:1)
回答by AkademiksQc
I know i am l8 to the party but did you look into NSMutableOrderedSet ?
我知道我是派对的 18 岁,但你有没有研究过 NSMutableOrderedSet ?
https://developer.apple.com/reference/foundation/nsorderedset
https://developer.apple.com/reference/foundation/nsorderedset
You can use ordered sets as an alternative to arrays when the order of elements is important and performance in testing whether an object is contained in the set is a consideration—testing for membership of an array is slower than testing for membership of a set.
当元素的顺序很重要并且需要考虑测试对象是否包含在集合中时的性能时,您可以使用有序集合作为数组的替代方案——测试数组的成员资格比测试集合的成员资格慢。
回答by enes
Swift does not include any built-in ordered dictionary capability, and as far as I know, Swift 2 doesn't either
Swift 不包含任何内置的有序字典功能,据我所知,Swift 2 也不包含
Then you shall create your own. You can check out these tutorials for help:
然后你将创建你自己的。您可以查看这些教程以获取帮助:
回答by Deep Parekh
if your keys confirm to Comparable, you can create a sorted dictionary from your unsorted dictionary as follows
如果您的键确认为 Comparable,您可以从未排序的字典中创建一个排序的字典,如下所示
##代码##回答by Jay Zi
回答by NoLongerContributingToSE
As others have said, there's no built in support for this type of structure. It's possible they will add an implementation to the standard library at some point, but given it's relativelyrare for it to be the best solution in most applications, so I wouldn't hold your breath.
正如其他人所说,这种类型的结构没有内置支持。他们可能会在某个时候将一个实现添加到标准库中,但鉴于它在大多数应用程序中成为最佳解决方案的情况相对罕见,所以我不会屏住呼吸。
One alternative is the OrderedDictionaryproject. Since it adheres to BidirectionalCollection
you get most of the same APIs you're probably used to using with other Collection
Types, and it appears to be (currently) reasonably well maintained.
一种替代方法是OrderedDictionary项目。由于它坚持BidirectionalCollection
您获得大部分相同的 API,您可能习惯于与其他Collection
类型一起使用,并且它似乎(目前)维护得相当好。