Ordered map in Swift

前端 未结 12 1137
忘掉有多难
忘掉有多难 2020-11-28 09:24

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

相关标签:
12条回答
  • 2020-11-28 10:06

    Swift does not include any built-in ordered dictionary capability, and as far as I know, Swift 2 doesn't either

    Then you shall create your own. You can check out these tutorials for help:

    • http://timekl.com/blog/2014/06/02/learning-swift-ordered-dictionaries/
    • http://www.raywenderlich.com/82572/swift-generics-tutorial
    0 讨论(0)
  • 2020-11-28 10:07

    "If you need an ordered collection of key-value pairs and don’t need the fast key lookup that Dictionary provides, see the DictionaryLiteral type for an alternative." - https://developer.apple.com/reference/swift/dictionary

    0 讨论(0)
  • 2020-11-28 10:10

    You can use KeyValuePairs, from documentation:

    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.

    let pairs: KeyValuePairs = ["john": 1,"ben": 2,"bob": 3,"hans": 4]
    print(pairs.first!)
    

    //prints (key: "john", value: 1)

    0 讨论(0)
  • 2020-11-28 10:10

    if your keys confirm to Comparable, you can create a sorted dictionary from your unsorted dictionary as follows

    let sortedDictionary = unsortedDictionary.sorted() { $0.key > $1.key }
    
    0 讨论(0)
  • 2020-11-28 10:14

    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).

    0 讨论(0)
  • 2020-11-28 10:15

    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 relatively rare for it to be the best solution in most applications, so I wouldn't hold your breath.

    One alternative is the OrderedDictionary project. 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.

    0 讨论(0)
提交回复
热议问题