Jake2Finn
Jake2Finn

Reputation: 536

populate 2d array with strings in special order

I want to populate my 2d array with a couple of array items. However, I can only figure out how to append one array after the other. What I actually want is to create a new array within my 2d array which contains certain items from the simple array. like this:

// required result myServerInfos = [ ["www.apple.com", "error", "no data"] ["www.google.com", "error", "no data"] ["www.amazon.com", "error", "no data"] ["www.bla.com", "error", "no data"] ]

These are my arrays:

swift 4

var myServerInfos = [[String]]()

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"]

I know I can access the first array item via "pings.first" and I know I should loop through each of the four arrays, save each of items in a new array and then append them to myServerInfos. I just cannot figure out how to do that concretely.

Upvotes: 1

Views: 48

Answers (3)

nycynik
nycynik

Reputation: 7541

In case you are looking for code that reads like your text:

var myServerInfos = [[String]]()

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 0 ..< pings.count {
    // one liner version
    let na = [ pings[i], statusImagesMain[i], serverStatusMain[i] ]

    /* shows append use for pushing items.
    var na = [String]()        
    na.append(pings[i])
    na.append(statusImagesMain[i])
    na.append(serverStatusMain[i])
    */

    // push array in
    myServerInfos.append(na)
}

Upvotes: 0

Martin R
Martin R

Reputation: 539765

zip() is useful to iterate two arrays (or more generally, sequences) in parallel. There is at present no corresponding zip function which takes more than 2 sequences, but with nested zip() calls you can get the required result with

let myServerInfos = zip(zip(pings, statusImagesMain), serverStatusMain).map {
    [$0.0, $0.1, $1]
}

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

let myServerInfos = (0..<pings.count).map{ 
  [pings[$0],statusImagesMain[$0],serverStatusMain[$0]] 
}

sure all must be of same size

Upvotes: 1

Related Questions