Swift:如何在 Swift 中声明二维数组(网格或矩阵)以允许随机插入

Swift: How to declare a 2d array (grid or matrix) in Swift to allow random insert(Swift:如何在 Swift 中声明二维数组(网格或矩阵)以允许随机插入)
本文介绍了Swift:如何在 Swift 中声明二维数组(网格或矩阵)以允许随机插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够将有关单元格的信息存储在二维矩阵或网格中.数据不是连续的,所以当较低的行和列没有数据时,我可能需要将数据存储在 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 中声明二维数组(网格或矩阵)以允许随机插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
appearance().setBackgroundImage Not Working On Custom Class(外观().setBackoundImage在自定义类上不起作用)
Show/Hide barButtonItem(显示/隐藏barButtonItem)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)