如何创建与大小斯威夫特空二维数组 [英] How to create Swift empty two dimensional array with size

查看:97
本文介绍了如何创建与大小斯威夫特空二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试做水木清华这样的:

I try to do smth like this:

let myArray: [[MyClass]] = [5,5]

其中[5,5]是阵列的尺寸。
我不能做到这一点。

where [5,5] is size of array. I can't do this.

推荐答案

如果你想使一个值类型的多维数组(即内部 S,字符串 S,结构),在codester的回答语法的伟大工程:

If you want to make a multidimensional array of value types (i.e. Ints, Strings, structs), the syntax in codester's answer works great:

var arr = [[Int]](count: 5, repeatedValue: [Int](count: 5, repeatedValue: 0))
arr[0][1] = 1
// arr is [[0, 1, 0, 0, 0], ...

如果您引用类型(即类),这可以让你多引用数组对同一对象的多维数组:

If you make a multidimensional array of reference types (i.e. classes), this gets you an array of many references to the same object:

class C {
    var v: Int = 0
}
var cArr = [[C]](count: 5, repeatedValue: [C](count: 5, repeatedValue: C()))
// cArr is [[{v 0}, {v 0}, {v 0}, {v 0}, {v 0}], ...
cArr[0][1].v = 1
// cArr is [[{v 1}, {v 1}, {v 1}, {v 1}, {v 1}], ...

如果你想使一个数组引用类型(单向或多维的),你可能会更好做任何阵列动态:

If you want to make an array (uni- or multidimensional) of reference types, you might be better off either making the array dynamically:

var cArr = [[C]]()
for _ in 0..<5 {
    var tmp = [C]()
    for _ in 0..<5 {
        tmp += C()
    }
    cArr += tmp
}
// cArr is [[{v 0}, {v 0}, {v 0}, {v 0}, {v 0}], ...
cArr[0][1].v = 1
// cArr is [[{v 0}, {v 1}, {v 0}, {v 0}, {v 0}], ...

(见 slazyk的回答使用相当于缩短语法地图()

或进行自选的数组,并在它们的值填充:

Or making an array of optionals and filling in their values:

var optArr = [[C?]](count: 5, repeatedValue: [C?](count: 5, repeatedValue: nil))
// optArr is [[nil, nil, nil, nil, nil], ...
optArr[0][1] = C()
// optArr is [[nil, {v 0}, nil, nil, nil], ...

这篇关于如何创建与大小斯威夫特空二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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