Home > Software engineering >  Compare each element in two arrays Swift
Compare each element in two arrays Swift

Time:03-22

I have two arrays of strings. for example:

let arrayFirst: [String] = ["A", "A", "A", "A", "A"]
let arraySecond: [String] = ["A", "C", "A", "B", "A"]

I need to compare this two arrays each element in array and return for every sequence bool state. For example here will be answer:

 let resultArray: [Bool] = [true, false, true, false, true]

how to do it better?

CodePudding user response:

You can consider using the zip function.

let resultArray = zip(arrayFirst, arraySecond).map {
    return $0.0 == $0.1
}

This will work even you have arrays of different length as zip will ignore the additional elements of the longer array.

  • Related