biedert
biedert

Reputation: 208

Sorting a struct array or dictionary in Swift

I have a struct dictionary like this (Taken from Swift: How to declare a 2d array (grid or matrix) in Swift to allow random insert , thanks to @rintaro ):

struct Matrix2D<KeyElem:Hashable, Value> {

    var _storage:[KeyElem:[KeyElem:Value]] = [:]

    subscript(x:KeyElem, y:KeyElem) -> Value? {
        get {
            return _storage[x]?[y]
        }
        set(val) {
            if _storage[x] == nil {
                _storage[x] = [:]
            }
            _storage[x]![y] = val
        }
    }
}

Now I would like to sort this dictionary by x, but I can't find a way to achieve this. Is it event possible to sort a dictionary? Or should I maybe use the solution with an Array instead of a Dictionary?

struct Matrix2D<T> {

    var _storage:[[T?]] = []

    subscript(x:Int, y:Int) -> T? {
        get {
            if _storage.count <= x {
            return nil
            }
            if _storage[x].count <= y {
                return nil
            }
            return _storage[x][y]
        }
        set(val) {
            if _storage.count <= x {
                let cols = [[T?]](count: x - _storage.count + 1, repeatedValue: [])
                _storage.extend(cols)
            }
            if _storage[x].count <= y {
                let rows = [T?](count: y - _storage[x].count + 1, repeatedValue: nil)
                _storage[x].extend(rows)
            }
            _storage[x][y] = val
        }
    }
}

Thanks for your help!

Upvotes: 0

Views: 357

Answers (1)

vadian
vadian

Reputation: 285072

A dictionary is per definition a collection type containing unordered key - value pairs.

There are some solutions for ordered dictionaries using a backing array, see for example earning-swift-ordered-dictionaries

Upvotes: 0

Related Questions