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

时间:2017-05-17 06:14:47

标签: ios arrays swift append traversal

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

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

直到现在我才得到最终= [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!"
            }

        }

1 个答案:

答案 0 :(得分:0)

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