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 Answers 2

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

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

Comments

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

4 Comments

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!
@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
@LeoDabus. Thank you! How do I subtract one from the indices properties?
@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.

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.