找到字符串后遍历整个数组

Traversing the complete array even after finding the string

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

现在我想要的是创建一个数组,其中包含 id 为 1 的数组 a 的项目,它应该是 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!"
            }

        }
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),它总是 return 找到 v_targetapplication 的第一个索引,在您的情况下是 1