我试图遍历整个数组,直到找到特定元素为止,即使找到该元素,也一直在起作用,直到第一次找到为止。
就像我有一个名为a = [a,b,c,d] //((prodname)的数组)及其其他id的数组i = [0,1,1,1] // prodAppid
现在,我要创建一个数组,该数组将具有ID为1的数组a的项,该数组的值应为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!"
}
}
最佳答案
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
。