1

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!

4 Answers 4

8

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]

Sign up to request clarification or add additional context in comments.

Comments

2

Try this

let a1 = ["1", "2", "3"]
let a2 = ["3", "2", "3"]

let result = zip(a1, a2).map({ $0 == $1 }).reduce(true, {$0 && $1})

Comments

0

Use a for loop:

for i in 0..<a1.length {
    if a1[i] != a2[i] {
        print("Index \(i) is not the same")
    }
}

Generally if you find yourself repeating the same code but with different numbers, you can substitute it with a for loop.

2 Comments

Thank you! Would the same for - loop work if the values were strings instead of integers?
@3Beard This loop does not make any assumptions about the types of a1 and a2 elements, as long as != operator can be applied.
0

Surely you could do something like this:

let a1 = ["1", "2", "3"]
let a2 = ["3", "2", "3"]

var compareResult : [String] = [String]()

if a1.count == a2.count { // Need to check they have same length

    for count in 0..<a1.count {
        let result : String = a1[count] == a2[count] ? "MATCH" : "MISMATCH"
        compareResult.append(result)
    }

    print(compareResult)
    // Do something more interesting with compare result...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.