Xcode Swift - How to initialize 2D array from [[AnyObject]] from many elements you want

I know I can initialize the Ints array like:

var intArray = [Int](count: 10, repeatedValue: 0)

      

I want to do 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 initializers available)

With the same result as initializing the array, for example:

var anyObjectArray : [[AnyObject]] = [[],[],[],[],[],[]]

      

But doing the above is ugly if I need for example 100 lines of say 3

The problem is that I can add to my function:

// init array
var anyObjectArray : [[AnyObject]] = [[],[],[]]

//inside a for loop
anyObjectArray[i].append(someValue)

      

This works fine until, of course, I get more number of rows in the array. The answer to this problem is also acceptable if I can do something like:

anyObjectArray[append a empty row here][]

      

But this is probably stupid :)

I hope there is a way to do this because I don't like having a line like:

var anyObjectArray : [[AnyObject]] = [ [],[],[],[],[],[],[],[],[],[],[],[],[],[],[], ... etc ]

      

at the top of my page;)

Thank you for your time!

+3


source to share


5 answers


You don't need a second initializer repeatedValue

as you need an empty array. You can just use



var array = Array(count:6, repeatedValue:[AnyObject]())

      

+6


source


You can try with 2 loops, working like a grid:



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

      

+1


source


Try to use

let array = Array(count:6, repeatedValue:[])

for (var i=0; i<array.count; i++){
    array[i] = Array(count:0, repeatedValue: AnyObject.self)
} 

      

instead of your code.

0


source


try it

    let columns = 27
    let rows = 52
    var array = Array<Array<Double>>()
    for column in 0... columns {
        array.append(Array(count:rows, repeatedValue:Int()))
    }

      

0


source


Swift 3:

var array = Array(repeating:[AnyObject](),count:6)

      

0


source







All Articles