Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

swift - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a very common requirement so the standard library caters to it with a function, zip:*

for (a,b) in zip(seq1, seq2) {
    // a and b will be matching pairs from the two sequences
}

Unfortunately, as of right now, zip only does pairs, even though in theory it could be overloaded to do triples. However, it’s not a big deal, you can just nest them:

var names = ["Joe", "Sarah", "Chad"]
var ages = [18, 20, 22]
var genders: [Gender] = [.Male, .Female, .Male]

for (name,(age,gender)) in zip(names,zip(ages,genders)) {
    makeUser(name, userAge: age, userGender: gender)
}

Note, it will only serve up to the shortest sequence, so if there are more names than ages or genders, you’ll only get the matching names.

This might seem like a down side compared to using an index, and this might also seem more complex, but the alternative’s simplicity is deceptive. Bear in mind what would happen if you used indices or enumerate alongside arrays that didn’t match – you’d get an array out of bounds assertion (or you’d have to put in checking logic).

zip avoids this problem. It also means you can use sequences instead of collections, as well as working with collections that don’t have integer indices (unlike enumerate) or collections that have different index types (e.g. a String and an Array).

*(in the current beta, anyway – zip returns a Zip2 object. In Swift 1.1, you need to create the Zip2 version directly as zip has only just been introduced)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...