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
// result : ["some1-some1","some2-some2","some3"]
You can use
zip()
, which creates a sequence of pairs from the two given sequences: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.
That should do it. Never used swift before so make sure to test.
You could also
enumerate
over one array and used the index to look inside the second array:Swift 1.2:
Swift 2:
Swift 3:
With Swift 4.2, you can use one of the 4 following Playground codes in order to solve your problem.
#1. Using
zip(_:_:)
functionIn the simplest case, you can use
zip(_:_:)
to create a new sequence of pairs (tuple) of the elements of your initial arrays.#2. Using
Array
'smakeIterator()
method and a while loopIt is also easy to loop over two arrays simultaneously with a simple while loop and iterators:
#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 toSequence
protocol, you can use instances of it directly in a for loop:#4. Using
AnyIterator
As an alternative to the previous example, you can use
AnyIterator
. The following code shows a possible implementation of it inside anArray
extension method:Try This: