Jake2Finn
Jake2Finn

Reputation: 536

populate multidimensional struct array with array data

I have some arrays which I am filling with data in my application. So when I initialize it, the arrays are - to some part - empty.

When my arrays are filled with all nessecary data, I want to save them in a multidimensional array in order to populate a table with this data, which is ordered by sections.

However, I am struggling how to append this multidimensional array with data.

This is what I want to have in my multidimensional array in the end:

data in myServerInfo: 

serverInfo(
    [ping: "www.apple.com", serverStatusMain: "no data", statusImagesMain: "error"],

    [ping: "www.google.com", serverStatusMain: "no data", statusImagesMain: "error"],

    [ping: "www.amazon.com", serverStatusMain: "no data", statusImagesMain: "error"],

    [ping: "www.bla.com", serverStatusMain: "no data", statusImagesMain: "error"]
    )

My current implementation looks like this:

struct serverInfo {
    var pings: String
    var serverStatusMain: String
    var statusImageMain: String
}

var myServerInfo: [[serverInfo]] = []


let pings = ["www.apple.com", "www.google.com", "www.amazon.com", "www.bla.com"]
var statusImagesMain = ["error", "error", "error", "error"]
var serverStatusMain = ["no data", "no data", "no data", "no data"]

for i in serverStatusMain { //
    myServerInfo.append([serverInfo(pings: pings[i], serverStatusMain: serverStatusMain[i], statusImageMain: statusImagesMain[i])])
}

Upvotes: 0

Views: 60

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

You need to append it like this.

for i in 0..<serverStatusMain.count {
    myServerInfo.append(serverInfo(pings: pings[i], serverStatusMain: serverStatusMain[i], statusImageMain: statusImagesMain[i]))
}

You made 2 mistakes:

  • You need i to have the index of the array to iterate through it.

  • You need to append an instance of an array for which you don't need to enclose it within [].

However if you need to append an array you can do it using the other append method.

myServerInfo.append(contentsOf: serverInfoArray) // serverInfoArrat would be an array -> [serverInfo]

Upvotes: 1

Related Questions