0

How do I iterate through multiple arrays in a for loop. I am aware of the zip method, but what if i have 9 arrays?

var usernames        = [String]()
var avatars          = [PFFile]()
var postDescriptions = [String]()
var locations        = [String]()
var latitudes        = [String]()
var longitudes       = [String]()
var postFiles        = [PFFile]()
var dates            = [Date]()
var uniqueIDs        = [String]()

and as you can see, they are of multiple formats.

2
  • 6
    o_O You should refactor the code to use a struct if you have 9 parallel arrays. Commented Jan 28, 2017 at 18:33
  • 2
    You should not have 9 arrays, you should have one User class and one array of instances of that class. Commented Jan 28, 2017 at 18:33

1 Answer 1

3

zip itself it a sequence, so in principle you could write:

for (username, (avatar, (postDescription, (location, (latitude, (longitude, (postFile, (date, uniqueID)))))))) 
    in zip(usernames, zip(avatars, zip(postDescriptions, zip(locations, zip(latitudes, zip(longitudes, zip(postFiles, zip(dates, uniqueIDs)))))))) {
        // use `username`, `avatar` etc.
}

(See also How can I run through three separate arrays in the same for loop? for other options)

Alas, look at this mess! 😫 You should really just define a structure that contains all 9 attributes:

struct User {
    var username: String
    var avatar: PFFile
    var postDescription: String
    var location: String
    var latitude: String
    var longitude: String
    var postFile: PFFile
    var date: Date
    var uniqueID: String
}

and then work on one array only:

var users = [User]()

for user in users {
    // use `user.username`, `user.avatar` etc.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.