循环数组,删除唯一值,只留下重复项

时间:2017-02-26 15:58:43

标签: swift

我有一个数组

allIDs = ["1", "2", "2", "3", "4", "4"]

我使用

制作了独特的内容
sortedIDs = Array(Set(allIDs))

现在我想删除allIDs数组中的唯一字符串,这样所有剩下的都是重复的。

for item in sortedIDs {
while allIDs.contains(item) {
    if let itemToRemoveIndex = allIDs.index(of: item) {
        allIDs.remove(at: itemToRemoveIndex)
        print(allIDs)
    }
}

}

这给了我一个空的allIDs数组。我很难过应该循环四次的for循环循环六次并删除所有项目。 感谢。

1 个答案:

答案 0 :(得分:0)

我假设你想要的结果是["2", "4"];从原始数组中删除的重复数组,以获取sortedIDs数组。

您的问题是循环的while循环,直到从allIDs删除了所有项目副本。如果您只是为sortedIDs中的每个项目执行1次移除,您将获得所需的结果:

for item in sortedIDs {
    if let itemToRemoveIndex = allIDs.index(of: item) {
        allIDs.remove(at: itemToRemoveIndex)
        print(allIDs)
    }
}