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
749 views
in Technique[技术] by (71.8m points)

swift - Iterate over two arrays simultaneously

I am new to Swift. I have been doing Java programming. I have a scenario to code for in Swift.

The following code is in Java. I need to code in Swift for the following scenario

// With String array - strArr1
String strArr1[] = {"Some1","Some2"}

String strArr2[] = {"Somethingelse1","Somethingelse2"}

for( int i=0;i< strArr1.length;i++){
    System.out.println(strArr1[i] + " - "+ strArr2[i]);
}

I have a couple of arrays in swift

var strArr1: [String] = ["Some1","Some2"]
var strArr2: [String] = ["Somethingelse1","Somethingelse2"]

for data in strArr1{
    println(data)
}

for data in strArr2{
    println(data)
}
// I need to loop over in single for loop based on index.

Could you please provide your help on the syntaxes for looping over based on index

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use zip(), which creates a sequence of pairs from the two given sequences:

let strArr1 = ["Some1", "Some2"]
let strArr2 = ["Somethingelse1", "Somethingelse2"]

for (e1, e2) in zip(strArr1, strArr2) {
    print("(e1) - (e2)")
}

The sequence enumerates only the "common elements" of the given sequences/arrays. If they have different length then the additional elements of the longer array/sequence are simply ignored.


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

...