Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 886
Lohith Avatar asked Mar 23 '15 18:03

Lohith


People also ask

How do you iterate two arrays in Python?

Use the izip() Function to Iterate Over Two Lists in Python It iterates over the lists until the smallest of them gets exhausted. It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.

Is it possible to iterate over arrays?

Iterating over an arrayYou can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

Can you iterate over sets?

There is no way to iterate over a set without an iterator, apart from accessing the underlying structure that holds the data through reflection, and replicating the code provided by Set#iterator...


2 Answers

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.

like image 145
Martin R Avatar answered Sep 26 '22 02:09

Martin R


With Swift 5, you can use one of the 4 following Playground codes in order to solve your problem.


#1. Using zip(_:_:) function

In the simplest case, you can use zip(_:_:) to create a new sequence of pairs (tuple) of the elements of your initial arrays.

let strArr1 = ["Some1", "Some2", "Some3"] let strArr2 = ["Somethingelse1", "Somethingelse2"]  let sequence = zip(strArr1, strArr2)  for (el1, el2) in sequence {     print("\(el1) - \(el2)") }  /*  prints:  Some1 - Somethingelse1  Some2 - Somethingelse2  */ 

#2. Using Array's makeIterator() method and a while loop

It is also easy to loop over two arrays simultaneously with a simple while loop and iterators:

let strArr1 = ["Some1", "Some2", "Some3"] let strArr2 = ["Somethingelse1", "Somethingelse2"]  var iter1 = strArr1.makeIterator() var iter2 = strArr2.makeIterator()  while let el1 = iter1.next(), let el2 = iter2.next() {     print("\(el1) - \(el2)") }  /*  prints:  Some1 - Somethingelse1  Some2 - Somethingelse2  */ 

#3. Using a custom type that conforms to IteratorProtocol

In some circumstances, you may want to create you own type that pairs the elements of your initials arrays. This is possible by making your type conform to IteratorProtocol. Note that by making your type also conform to Sequence protocol, you can use instances of it directly in a for loop:

struct TupleIterator: Sequence, IteratorProtocol {      private var firstIterator: IndexingIterator<[String]>     private var secondIterator: IndexingIterator<[String]>      init(firstArray: [String], secondArray: [String]) {         self.firstIterator = firstArray.makeIterator()         self.secondIterator = secondArray.makeIterator()     }      mutating func next() -> (String, String)? {         guard let el1 = firstIterator.next(), let el2 = secondIterator.next() else { return nil }         return (el1, el2)     }  }  let strArr1 = ["Some1", "Some2", "Some3"] let strArr2 = ["Somethingelse1", "Somethingelse2"]  let tupleSequence = TupleIterator(firstArray: strArr1, secondArray: strArr2)  for (el1, el2) in tupleSequence {     print("\(el1) - \(el2)") }  /*  prints:  Some1 - Somethingelse1  Some2 - Somethingelse2  */ 

#4. Using AnyIterator

As an alternative to the previous example, you can use AnyIterator. The following code shows a possible implementation of it inside an Array extension method:

extension Array {      func pairWithElements(of array: Array) -> AnyIterator<(Element, Element)> {         var iter1 = self.makeIterator()         var iter2 = array.makeIterator()          return AnyIterator({             guard let el1 = iter1.next(), let el2 = iter2.next() else { return nil }             return (el1, el2)         })     }  }  let strArr1 = ["Some1", "Some2", "Some3"] let strArr2 = ["Somethingelse1", "Somethingelse2"]  let iterator = strArr1.pairWithElements(of: strArr2)  for (el1, el2) in iterator {     print("\(el1) - \(el2)") }  /*  prints:  Some1 - Somethingelse1  Some2 - Somethingelse2  */ 
like image 32
Imanou Petit Avatar answered Sep 24 '22 02:09

Imanou Petit