Xcode Swift - 如何初始化包含任意数量元素的 [[AnyObject]] 二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27876274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Xcode Swift - How to initialize a 2D array of [[AnyObject]] of as many elements you want
提问by Henk-Martijn
I know I can initialize an array of Ints for example like:
我知道我可以初始化一个 Int 数组,例如:
var intArray = [Int](count: 10, repeatedValue: 0)
What I want to do is something like this:
我想做的是这样的:
var array = Array(count:6, repeatedValue:Array(count:0, repeatedValue:AnyObject()))
(Xcode returns with: AnyObject cannot be constructed because it has no accessible initializers)
(Xcode 返回: AnyObject 无法构造,因为它没有可访问的初始值设定项)
With the same outcome as I could initialize the array like:
与我可以初始化数组的结果相同:
var anyObjectArray : [[AnyObject]] = [[],[],[],[],[],[]]
But doing the above is ugly if i need like 100 rows of lets say 3
但是如果我需要 100 行让我们说 3
The problem is I can append in my function like:
问题是我可以在我的函数中附加:
// init array
var anyObjectArray : [[AnyObject]] = [[],[],[]]
//inside a for loop
anyObjectArray[i].append(someValue)
That works ok, until of course i gets higher then the number of rows in the array. A answer to this problem is also acceptable if I could do something like:
这工作正常,直到我当然变得高于数组中的行数。如果我可以执行以下操作,则此问题的答案也是可以接受的:
anyObjectArray[append a empty row here][]
But that is probably stupid :)
但这可能是愚蠢的:)
I hope there is a way to do this cause I don't feel like having a line like:
我希望有一种方法可以做到这一点,因为我不想有这样的一行:
var anyObjectArray : [[AnyObject]] = [ [],[],[],[],[],[],[],[],[],[],[],[],[],[],[], ... etc ]
at the top of my page ;)
在我的页面顶部 ;)
Thank you for your time!
感谢您的时间!
回答by Paulw11
You don't need the second repeatedValue
initialiser, since you want an empty array. You can just use
您不需要第二个repeatedValue
初始化程序,因为您需要一个空数组。你可以使用
var array = Array(count:6, repeatedValue:[AnyObject]())
回答by Kalzem
You can try with 2 loops, working as a grid :
您可以尝试使用 2 个循环,作为网格工作:
var items: = Array<Array<Item>>()
for col in 0..<maxCol {
var colItems = Array<Item>()
for row in 0..<maxRow {
colItems.append(Item())
}
items.append(colItems)
}
//Append as much as you want after
回答by Krishna
Try using this
尝试使用这个
let array = Array(count:6, repeatedValue:[])
for (var i=0; i<array.count; i++){
array[i] = Array(count:0, repeatedValue: AnyObject.self)
}
in place of your code.
代替您的代码。
回答by Christos Chadjikyriacou
Try this
尝试这个
let columns = 27
let rows = 52
var array = Array<Array<Double>>()
for column in 0... columns {
array.append(Array(count:rows, repeatedValue:Int()))
}
回答by Nithin Dev N
Swift 3:
斯威夫特 3:
var array = Array(repeating:[AnyObject](),count:6)