Swift 3 comparing array indexes

2019-09-14 19:58发布

问题:

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!

回答1:

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]



回答2:

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.



回答3:

Try this

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

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


回答4:

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...
}