Home > database >  Comparing elements at different indices in array Swift
Comparing elements at different indices in array Swift

Time:02-14

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related