lukaskubanek / OrderedDictionary

Ordered dictionary data structure implementation in Swift
MIT License
201 stars 63 forks source link

Need sample code #29

Closed balakrishnaJarugubelli closed 7 years ago

balakrishnaJarugubelli commented 7 years ago

Hi,

Could you please provide sample code and documentation??

I have a unsorted dictionary. how can I use your library to make it as orderdDict

It's bit tricky with init methods(Elements/Sequences). Please suggest as I am new to Swift.

Thanks in advance.

lukaskubanek commented 7 years ago

Hi, you can find sample code in the playground included in the repository. For API documentation please refer to the comments in the source files. I will eventually turn the code comments into an API documentation using Jazzy in #24.

Regarding your specific problem, there is actually not a simple way for doing it. I might add a secondary initializer which would take a dictionary and a sort function in the future (see #30). For now you have to construct the elements sequence from the dictionary on your own and apply custom sorting. Here is an example:

let dictionary = [
    1: "foo",
    2: "bar",
    3: "baz"
]

let unsortedElements = dictionary .map { key, value in
    return (key: key, value: value)
}

let sortedElements = unsortedElements.sorted { element1, element2 in
    return element1.key < element2.key
}

let orderedDictionary = OrderedDictionary<Int, String>(sortedElements)