Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

collections - Swift: How to declare a 2d array (grid or matrix) in Swift to allow random insert

I need to be able to store information about cells in a 2d matrix or grid. Data is not contiguous so I may need to store data at 5,5 when there is no data at lower rows and columns.

My first thought was an array of arrays dynamically sized. But Swift arrays have bounds that do not grow automatically. If I attempt to place something at index 5 and thats beyond its current size it fails with out of bounds exception.

Is there a collection class in Swift or Cocoa which supports random access to a grid. NSArray doesn't support it either.

Another thought was to store the elements in a dictionary and use a tuple of row, column as the key. However, tuples are not hashable and can't be used as the key to a dictionary.

My current approach is to preinitialize the array with a set size filled with nulls. Is there a better way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a very basic implementation, using Dictionary as backend storage:

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
        }
    }
}

var matrix = Matrix2D<Int, String>()

matrix[1,2] = "foo"

as DictionaryLiteralConvertible:

extension Matrix2D:DictionaryLiteralConvertible {

    typealias Key = (x:KeyElem, y:KeyElem)

    init(dictionaryLiteral elements: (Key, Value)...) {
        for (key, val) in elements {
            self[key.x, key.y] = val
        }
    }
}

var matrix:Matrix2D = [(1,2):"foo", (2,3):"bar"]

Array backend version

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
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...