Andrew Carnige Andrew Carnige - 26 days ago 13
Swift Question

How can I run through three separate arrays in the same for loop?

I have three arrays I am trying to run through and I want to use the values from all three arrays in one function. This might sound confusing but here is what I have:

var Name = [Joe, Sarah, Chad]
var Age = [18, 20, 22]
var Gender = [Male, Female, Male]

for name in Name {
for age in Age {
for gender in Gender {
makeUser(name, userAge: age, userGender: gender)
}
}
}


This runs but what I get is: (makeUser prints out the 3 values)

Joe, 18, Male
Joe, 20, Male
Joe, 22, Male

Joe, 18, Female
Joe, 20, Female
Joe, 22, Female ....


And so on.

All I want is

Joe, 18, Male
Sarah, 20, Female
Chad, 22, Male


Is this possible? Any help is appreciated.

Thanks!

Answer

If you are always sure the arrays will be equal in length, then you are better to just loop through one of the arrays and use it's index to reference the others:

for (index, name) in enumerate(Name) {
    makeUser(name, userAge: Age[index], userGender: Gender[index])
}

However, I would recommend getting this data into a dictionary, but I assume this is just sample data to illustrate a point. :)