【问题标题】:Comparing elements at different indices in array Swift比较数组Swift中不同索引处的元素
【发布时间】:2022-02-14 08:25:56
【问题描述】:

在 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'

我该如何解决这个问题?

【问题讨论】:

    标签: arrays swift indexing comparison


    【解决方案1】:

    不是对您的问题的直接回答,但如果您想要比较集合中的相邻元素,您需要使用相同的集合压缩集合,删除第一个元素:

    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
    做点什么
    1 != 2
    什么都不做

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这几乎可以工作,我得到一个越界错误,但它来自于对 if 语句进行比较。如果我将其更改为 myArray.count -1 我可以绕过该错误。谢谢!
      • @KyleZeller 不要使用集合计数属性来迭代集合。并非所有集合都包含所有元素。您应该始终使用它的索引。 for index in array.indices {。检查这个How to iterate a loop with index and element in Swift
      • @LeoDabus。谢谢!如何从索引属性中减去一个?
      • @KyleZeller 索引属性是不可变的,但您可以获取其内容并简单地删除元素,就像从数组中删除元素一样。你也可以 dropFirst(n) 或 dropLast(n) 如我下面的帖子所示。
      猜你喜欢
      • 2021-12-05
      • 1970-01-01
      • 2018-01-25
      • 2017-02-20
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多