Swift 循环数组,删除唯一值,只保留重复值
我有一个数组Swift 循环数组,删除唯一值,只保留重复值,swift,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.rem
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循环是如何循环六次并删除所有项的,我被难倒了。
谢谢。我假设您想要的结果是
[“2”,“4”]
;从原始阵列中删除以获取sortedID
阵列的重复阵列
您的问题是while
循环,该循环一直循环,直到项目的所有副本都从所有ID
中删除。如果您只需对sortedis
中的每个项目执行1次删除,您将得到想要的结果:
for item in sortedIDs {
if let itemToRemoveIndex = allIDs.index(of: item) {
allIDs.remove(at: itemToRemoveIndex)
print(allIDs)
}
}
@dtd,这不是重复的。OP已经知道如何删除重复项。问题在于创建一个只包含重复项的最终数组。您期望的结果是什么
[“2”、“2”、“4”、“4”]
或[“2”、“4”]
?@Honey:这个问题没有提到所需的输出–这就是为什么Hamish要求它。对于数组[“1”、“1”、“1”、“2”]
您的预期结果是什么?对于“一个应该循环四次的for循环是如何循环六次并删除所有项”的回答,我感到困惑is:使用调试器,或添加显示代码中发生的情况的打印语句。