3Beard - 1 year ago 69

Swift Question

If i have two arrays & i want to compare their indexes, for ex:

`let var a1 = ["1", "2", "3"]`

let var a2 = ["3", "2", "3"]

And i wanted to print something to say which index wasn't the same, such as:

`if a1[0] != a2[0] && a1[1] == a2[1] && a1[2] == a2[2]{`

print("Index 0 is not the same.")

Would i have to write 7 more of those statements to show all 8 possibilities of all correct/all wrong/index 1&1 wrong, etc?

Thank you!

Answer Source

You can get all indexes like this:

```
let diffIndex = zip(a1, a2).enumerated().filter {$1.0 != $1.1}.map {$0.offset}
```

Explanation:

`zip`

produces a sequence of pairs`enumerated()`

adds an index to the sequence`filter`

keeps only pairs with different values`map`

harvests the index, and builds the sequence of results.

Running this on

```
let a1 = ["1", "2", "3", "4"]
let a2 = ["3", "2", "3", "5"]
```

This produces a sequence `[0, 3]`