xcode 如何删除数组中的重复元素 - swift 3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42921166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove duplicate elements inside an array - swift 3
提问by S.M_Emamian
I want to remove duplicate elements from an array. there are many answers in stack overflow but for swift 3.
我想从数组中删除重复的元素。堆栈溢出有很多答案,但对于 swift 3。
my array:
我的阵列:
var images = [InputSource]()
... // append to array
how to remove duplicate elements from this array?
如何从此数组中删除重复元素?
Is there any native api from swift 3 ?
swift 3 是否有任何本机api?
回答by Sweeper
Make sure that InputSource
implements Hashable
, otherwise Swift can't know which elements are equal and which are not.
确保InputSource
implements Hashable
,否则 Swift 无法知道哪些元素相等,哪些不相等。
You just do this:
你只需这样做:
let withoutDuplicates = Array(Set(images))
Explanation:
解释:
images
is turned into a set first. This removes all the duplicates because sets can only contain distinct elements. Then we convert the set back to an array.
images
先变成一套。这将删除所有重复项,因为集合只能包含不同的元素。然后我们将集合转换回数组。
According to this answer, this is probably optimized by the compiler.
根据这个答案,这可能是由编译器优化的。
The disadvantage of this is that it might not preserve the order of the original array.
这样做的缺点是它可能不会保留原始数组的顺序。
回答by Lysdexia
You might want to use Set
您可能想使用 Set
// Initialize the Array
var sample = [1,2,3,4,5,2,4,1,4,3,6,5]
// 初始化数组
var sample = [1,2,3,4,5,2,4,1,4,3,6,5]
// Remove duplicates:
sample = Array(Set(sample))
// 删除重复项:
sample = Array(Set(sample))
print(sample)
print(sample)
回答by Frank Schlegel
If order is not important, you should use a Set
instead. Sets only contain unique elements. You can also create a Set
from the array, that should eliminate duplicates.
如果顺序不重要,则应使用 aSet
代替。集合仅包含唯一元素。您还可以Set
从数组中创建一个,以消除重复项。