【问题标题】:Traversing the complete array even after finding the string即使在找到字符串之后也遍历完整的数组
【发布时间】:2017-10-16 10:44:24
【问题描述】:

我正在尝试遍历整个数组直到最后寻找特定元素,即使找到它,直到它在第一次找到它之前一直在工作。 就像我有一个名为 a = [a,b,c,d]//(prodname) 的数组和它的 id 的其他数组 i = [0,1,1,1] // prodAppid

现在我想要创建一个数组,其中包含数组 a 的项,其 id 为 1,它应该是 final = [b,c,d] // TargetProducts1。

到目前为止,我得到了 final = [b,b,b],它不会更进一步。这是我的代码

  for items in prodAppid {

            if var i = prodAppid.index(of: v_targetapplication) {

                print("Product id is at index \(i)")
                print("product Name = \(prodname[i])")
                // product1Text.text = prodname[i]
                //      TargetProducts1.append([prodname[i]])
                TargetProducts1.append(prodname[i])
                print("Target products for this application = \(TargetProducts1)")



            } else {
                print("Product Doesn't exsit for this Application")
                product1Text.text = "No Product available for this Application!"
            }

        }

【问题讨论】:

  • 什么是v_targetapplication?它的价值是什么?

标签: ios arrays swift append traversal


【解决方案1】:
let names = ["a", "b", "c", "d"]
let ids = [0, 1, 1, 1]
let targetId = 1
let targetNames: [String] = ids.enumerated()
    .flatMap { (index, id) -> String? in
        return targetId == id ? names[index] : nil
    }

你的代码的问题是if var i = prodAppid.index(of: v_targetapplication),它总是返回找到v_targetapplication的第一个索引,在你的情况下是1

【讨论】:

  • 完美!!谢谢。
猜你喜欢
  • 2021-11-27
  • 2020-11-17
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 2014-06-16
相关资源
最近更新 更多