在Swift中寻址一个多维对象数组

时间:2016-02-13 15:33:04

标签: arrays swift

极端新手Swift语法问题......

尝试解决UIImageView对象的多维数组并获取错误

  

无法下标索引为[[UIImageView]]类型的值   输入UInt32。

我以为我正在创建一个UxmageView对象的NxN数组,但我想不是吗?

全部谢谢!

func loadDefaultImages()
{
    var pictures : [[UIImageView]] = [];
    let MaxRows: UInt32 = 4
    let MaxCols: UInt32 = 4
    var row: UInt32
    var col: UInt32

    for (row = 0; row <= MaxRows; row++)
    {
        for (col = 0; col <= MaxCols; col++)
        {
            var newImage = UIImageView(image: UIImage(named: "first"))
            pictures[row][col] = UIImageView() /* Error on this statement */

        }
    }
}

1 个答案:

答案 0 :(得分:0)

最初,您的pictures数组不包含任何元素(即它将评估为[])。当您尝试设置pictures[0][0]时,您尝试引用尚不存在的行和列。

相反,您可以随意构建阵列,如下所示:

func loadDefaultImages() {

    var pictures : [[UIImageView]] = [];
    let MaxRows: UInt32 = 4
    let MaxCols: UInt32 = 4

    for _ in 0..<MaxRows {
        var aRow : [UIImageView] = []
        for _ in 0..<MaxCols {
            let newImage = UIImageView(image: UIImage(named: "first"))
            aRow.append(newImage)
        }
        pictures.append(aRow)
    }
}

但是,更简单的方法是使用count, repeatedValue函数创建具有默认大小的数组,如下所示:

func loadDefaultImages() {

    let MaxRows: Int = 4
    let MaxCols: Int = 4

    var pictures = [[UIImageView?]](count: MaxRows, repeatedValue: [UIImageView?](count: MaxCols, repeatedValue: nil))

    for row in 0..<MaxRows {
        for col in 0..<MaxCols {
            let newImage = UIImageView(image: UIImage(named: "first"))
            pictures[row][col] = newImage
        }
    }
}