【问题标题】:refactor suggestion for my array iteration?重构我的数组迭代的建议?
【发布时间】:2020-09-27 13:49:42
【问题描述】:

我觉得我在下面做了一个更优雅的方式..有什么建议吗?

import Foundation

var bullet = ["aka","bz","cy"]

for i in bullet {
    if i.contains("ka") {
        let p = bullet.firstIndex(of: i)
        bullet[p!]
    }
}

【问题讨论】:

  • 您不需要contains 检查您是否使用firstIndex(of:)。只是有条件地打开它,而不是像你一样强制打开它
  • 请将所需的输出添加到问题中?
  • 如果我的数组包含任何值的 ka 我打印我的标签该值 aka 如果不是我打印 asdfgj 例如所以我需要找到它在哪里是哪个索引
  • 如果数组中有多个包含“ka”的值怎么办?

标签: ios arrays swift


【解决方案1】:

如果你想得到第一个匹配的值,那么你可以使用first,如果你想得到它的索引,你可以使用firstIndexif let是安全地解开一个可选值。

var bullet = ["aka","bz","cy"]


if let value = bullet.first(where: { $0.contains("ka") }) {
    print(value) //"aka"
}

if let index = bullet.firstIndex(where: { $0.contains("ka")}) {
    print(index) //0
}

【讨论】:

    【解决方案2】:

    您可以使用 filter(_:)contains(_:) 之类的,

    let arr = bullet.filter { $0.contains("ka") }
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      if let kaItem = bullet.first({ $0.contains(“ka”) }) {
          myLabel.text = kaItem
      } else {
          myLabel.text = “asdfghj”
      }
      

      如果需要获取索引并设置文本,可以使用firstIndex方法:

         if let kaItemIndex = bullet.firstIndex({ $0.contains(“ka”) }) {
              myLabel.text = bullet[kaItemIndex]
          } else {
              myLabel.text = “asdfghj”
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-20
        • 2021-03-07
        • 2016-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多