问题描述
我需要能够将有关单元格的信息存储在二维矩阵或网格中.数据不是连续的,所以当较低的行和列没有数据时,我可能需要将数据存储在 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.
我目前的方法是使用填充空值的设定大小预初始化数组.有没有更好的办法?
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"]
<小时>
数组
后端版本
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 中声明二维数组(网格或矩阵)以允许随机插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!