1

In swift, I want to compare two different indexes in the same array. Right now, My code is something like:

var myArray:[String] = ["1" , "1", "2"]

for i in myArray{
     if(myArray[i] == myArray[i + 1]){
     // do something
     } 
}

From this, I get an error:

Cannot convert value of type 'String' to expected argument type 'Int'

How do I go about fixing this?

2 Answers2

4

Not a direct answer to your question but if what you want is to compare adjacent elements in a collection what you need is to zip the collection with the same collection dropping the first element:

let array = ["1" , "1", "2"]

for (lhs,rhs) in zip(array, array.dropFirst()) {
     if lhs == rhs {
         print("\(lhs) = \(rhs)")
         print("do something")
     } else {
         print("\(lhs) != \(rhs)")
         print("do nothing")
     }
}

This will print:

1 = 1
do something
1 != 2
do nothing

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
1

For-each construction (for i in array) does not provide you with an index, it takes elements from a sequence.

You may want to use ranges like this to aquire indices: for i in 0 ..< array.count

The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49
  • that almost works, I get an out of bounds error, but it comes from doing the comparison on the if statement. If I change it to myArray.count -1 I can get around the error. Thank you! – Kyle Zeller Feb 13 '22 at 23:47
  • 1
    @KyleZeller don't use the collection count property to iterate a collection. Not all collections contains all elements. You should always us its indices. `for index in array.indices {`. Check this [How to iterate a loop with index and element in Swift](https://stackoverflow.com/a/54877538/2303865) – Leo Dabus Feb 14 '22 at 00:17
  • @LeoDabus. Thank you! How do I subtract one from the indices properties? – Kyle Zeller Feb 14 '22 at 00:27
  • @KyleZeller the indices properties is immutable but you can get its content and simply remove an element the same way you remove an element from an array. you can also dropFirst(n) or dropLast(n) as shown in my post bellow. – Leo Dabus Feb 14 '22 at 13:02