-1

I have two arrays with different types (classes) and amount of items there. When I try to loop through them, I loop as much times as much items in smaller array. I need it to loop through both and when smaller ends, larger one continue to loop. Hope to see some suggestions.

So, I have two arrays:

var humanArray = [human, cook, manager, fighter, astronaut]

and:

let alienArray = [martian, twixian, snikersian]

They are different classes:

 let human = People(name: "John Dou", height: 180, weight: 80, gender: "male")

and:

 let martian = Martian(numberOfLegs: 1, colorOfSkin: .red)

then I loop through them:

 for (hum, al) in zip(humanArray, alienArray) {
print("""
    \(hum.TypeName) \(hum.name),
    \(hum.TypeName) \(hum.height),
    \(hum.TypeName) \(hum.weight),
    \(hum.TypeName) \(hum.gender),
    \(al.TypeName) \(al.numberOfLegs),
    \(al.TypeName) \(al.colorOfSkin)
    """)

hum.say()
al.say()
}

So what should I do to get all the 5 iterations? Or how to do such thing (loop over two arrays) without "zip"? Without it, I have an error: Yes, they are ignored, but how to do this without "zip"? I have an error: "Type '([People], [Martian])' does not conform to protocol 'Sequence'".

My question is different than questions, that was asked before, because I have two arrays with different amount of items. And solutions, provided there, are not appropriate.

Artem Boordak
  • 211
  • 3
  • 15
  • When using `zip` if two arrays have different length then the additional elements of the longer array are simply ignored. So `fighter, astronaut` are not printed – RajeshKumar R Jun 13 '19 at 11:55
  • Yes, they are ignored, but how to do this without "zip"? I have an error: "Type '([People], [Martian])' does not conform to protocol 'Sequence'" – Artem Boordak Jun 13 '19 at 12:03
  • Use two for loops, one for each array – RajeshKumar R Jun 13 '19 at 12:07
  • Possible duplicate of [In Swift I would like to "join" two sequences in to a sequence of tuples](https://stackoverflow.com/questions/25153477/in-swift-i-would-like-to-join-two-sequences-in-to-a-sequence-of-tuples) – Joe Jun 13 '19 at 12:11
  • Given your example, what do you want it to print out? What do you want `al.colorOfSkin` to be when you've run out of aliens? – Rob Napier Jun 13 '19 at 17:05

2 Answers2

2

Working but pretty basic solution

for i in 0..<(max(arr1.count, arr2.count)) {
    if i < arr1.count {
        print(arr1[i])
    }
    if i < arr2.count {
        print(arr2[i])
    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
1

You can simply do,

var i = 0
for _ in 0..<min(alienArray.count, humanArray.count) {
    print(humanArray[i].name, alienArray[i].numberOfLegs)
    i += 1
}
print(humanArray[i...].compactMap({ $0.name }).joined(separator: " "))
print(alienArray[i...].compactMap({ $0.numberOfLegs }).joined(separator: " "))
PGDev
  • 23,751
  • 6
  • 34
  • 88