Iterate over two arrays simultaneously

Lohith picture Lohith · Mar 23, 2015 · Viewed 31.5k times · Source

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

Answer

Martin R picture Martin R · Mar 23, 2015

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.