比较数组 Swift 中不同索引处的元素

Comparing elements at different indices in array Swift

在swift中,我想比较同一个数组中的两个不同索引。现在,我的代码是这样的:

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

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

由此,我得到一个错误:

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

我该如何解决这个问题?

For-each 构造 (for i in array) 不为您提供索引,它从序列中获取元素。

您可能希望使用这样的范围来获取索引: for i in 0 ..< array.count

不是您问题的直接答案,但如果您想要比较集合中的相邻元素,则需要将集合与删除第一个元素的同一集合一起压缩:

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")
     }
}

这将打印:

1 = 1
do something
1 != 2
do nothing