Lonely Twinky Lonely Twinky - 3 months ago 16
Swift Question

How can I assign the values of one array to a multiple dimension array?

I am creating a multiple dimension array and I need to assign the column names to the array, but I keep getting the error:

Cannot convert the value of type String to expected argument of type

I am new to swift, so I don't really know what to do, so here is my code:

var data = [[[String]]]()
var rows = 3
var columns = 3
var column_names = ["Red", "Blue", "Green", "Orange"]
var index1 = 0

for index1 in 0...columns{
data[index1] = column_names[index1]

Answer Source

The code var data = [[[String]]]() creates an array of arrays of arrays. you need 3 indexes if you want to be able to insert a string into it.

Assuming you only want a 2-dimensional array, you might use code like this instead:

var data = [[String]]()

var column_names = ["Red", "Blue", "Green", "Orange"]
let rows = 3
let columns = column_names.count
let empty_row = Array(repeating: "", count: columns)

for _ in 1 ..< rows {


In the code above we create an empty 2 dimensional array. We then add an array of column names, followed by rows of empty strings.

Swift doesn't actually have a native n-dimensional array type. Instead, you create arrays that contain other arrays. Thus it's possible to create "jagged" arrays where the different sub-arrays have differing numbers of elements. In your case I'm assuming you want a 4x3 2-dimensional array, so that's what the code I wrote above creates.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download