迭代多个数组

时间:2017-01-28 18:32:37

标签: swift

如何在for循环中迭代多个数组。我知道zip方法,但是如果我有9个数组呢?

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]()

如您所见,它们有多种格式。

1 个答案:

答案 0 :(得分:3)

zip本身就是一个序列,所以原则上你可以写:

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

(另请参阅How can I run through three separate arrays in the same for loop?了解其他选项)

唉,看看这个烂摊子!您应该只定义一个包含所有9个属性的结构:

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
}

然后只处理一个数组:

var users = [User]()

for user in users {
    // use `user.username`, `user.avatar` etc.
}