Kareem Arab
Kareem Arab

Reputation: 13

Iterate through Multiple Arrays

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.

Upvotes: 0

Views: 739

Answers (1)

kennytm
kennytm

Reputation: 523154

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.
}

Upvotes: 3

Related Questions