【问题标题】:For loop used to search an array, Swift [duplicate]For循环用于搜索数组,Swift [重复]
【发布时间】:2019-05-03 01:47:47
【问题描述】:

我需要在对象数组中搜索特定值。
swift中是否有相当于Java中for(Distance d : distances)的功能。

【问题讨论】:

    标签: arrays swift


    【解决方案1】:

    你指的是for-in循环吗?

    let distances = [1, 2, 3, 4, 5]
    
    for distance in distances {
        if distance == something {
            // do something
            break
        }
    }
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      你可以使用类似下面的东西

      let arr = [1,2,3,4,5]
      let index = arr.firstIndex(of: 3)
      

      索引将给出匹配对象的第一个索引。 它还有其他变化。 在这里查看更多详情 https://developer.apple.com/documentation/swift/array/1848165-first

      更新:特定于您的查询

      struct Test {
          let number: Int
      }
      
      let arr = [Test(number: 1),Test(number: 2),Test(number: 3),Test(number: 4),Test(number: 5)]
      let index = arr.firstIndex(where: {$0.number == 4 })
      

      索引将给出匹配对象的第一个索引。

      【讨论】:

      • 我将如何为对象内部的 int 实现这个,因为我的数组是对象
      • @chad 用您的具体问题更新了答案。
      猜你喜欢
      • 2013-08-28
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多