Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
Comparing elements at different indices in array Swift

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!