Swift:如何在Swift中声明一个2d数组(网格或矩阵),以允许随机插入 [英] Swift: How to declare a 2d array (grid or matrix) in Swift to allow random insert

查看:251
本文介绍了Swift:如何在Swift中声明一个2d数组(网格或矩阵),以允许随机插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够在2d矩阵或网格中存储有关单元格的信息。数据不连续,所以我可能需要存储数据在5,5,当没有数据在较低的行和列。

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.

我的第一个想法是一个数组数组动态大小。但是Swift数组的边界不会自动增长。如果我试图将某些东西放在索引5,超出其当前的大小,它会失败,超出范围的异常。

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.

在Swift或Cocoa中有一个集合类支持随机访问网格。 NSArray不支持它。

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.

我当前的方法是使用填充了null的集合大小来初始化数组。
有更好的方法吗?

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

推荐答案

这是一个非常基本的实现,使用 Dictionary 作为后端存储:

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"

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"]


$ b b




数组后端版本

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

这篇关于Swift:如何在Swift中声明一个2d数组(网格或矩阵),以允许随机插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆