Ordered map in Swift

前端 未结 12 1138
忘掉有多难
忘掉有多难 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:15

    use Dictionary.enumerated()

    example:

    let dict = [
        "foo": 1,
        "bar": 2,
        "baz": 3,
        "hoge": 4,
        "qux": 5
    ]
    
    
    for (offset: offset, element: (key: key, value: value)) in dict.enumerated() {
        print("\(offset): '\(key)':\(value)")
    }
    // Prints "0: 'bar':2"
    // Prints "1: 'hoge':4"
    // Prints "2: 'qux':5"
    // Prints "3: 'baz':3"
    // Prints "4: 'foo':1"
    
    0 讨论(0)
  • 2020-11-28 10:16

    Here's what I did, pretty straightforward:

    let array = [
        ["foo": "bar"],
        ["foo": "bar"],
        ["foo": "bar"],
        ["foo": "bar"],
        ["foo": "bar"],
        ["foo": "bar"]
    ]
    
    // usage
    for item in array {
        let key = item.keys.first!
        let value = item.values.first!
    
        print(key, value)
    }
    

    Keys aren't unique as this isn't a Dictionary but an Array but you can use the array keys.

    0 讨论(0)
  • 2020-11-28 10:18
        var orderedDictionary = [(key:String, value:String)]()
    
    0 讨论(0)
  • 2020-11-28 10:22

    I know i am l8 to the party but did you look into NSMutableOrderedSet ?

    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.

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

    As Matt says, dictionaries (and sets) are unordered collections in Swift (and in Objective-C). This is by design.

    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.

    EDIT:

    For Swift Dictionaries it's someDictionary.keys

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

    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() { $0.name < $1.name }
    // or
    array.sort() { $0.0 < $1.0 }
    
    0 讨论(0)
提交回复
热议问题