本文介绍了是否存在斯威夫特的API中的一个简单的方法来从数组中删除重复的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能有一个数组,如下所示:

I might have an array that looks like the following:

[1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]

或者,真的,数据像类型的部分的任何序列。我想要做的就是确保只有每个有相同的元素之一。例如,上述的阵列将变成:

Or, really, any sequence of like-typed portions of data. What I want to do is ensure that there is only one of each identical element. For example, the above array would become:

[1, 4, 2, 6, 24, 15, 60]

注意,除去的2,6,和15的重复,以确保只有有每个相同的元素之一。斯威夫特是否提供了一种方法可以轻松地做到这一点,或者我会做我自己?

Notice that the duplicates of 2, 6, and 15 were removed to ensure that there was only one of each identical element. Does Swift provide a way to do this easily, or will I have to do it myself?

推荐答案

您可以滚动您自己,例如像这样(的更新雨燕1.2与集

You can roll your own, e.g. like this (updated for Swift 1.2 with Set):

func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] {
    var buffer = [T]()
    var added = Set<T>()
    for elem in source {
        if !added.contains(elem) {
            buffer.append(elem)
            added.insert(elem)
        }
    }
    return buffer
}

let vals = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
let uniqueVals = uniq(vals) // [1, 4, 2, 6, 24, 15, 60]

这篇关于是否存在斯威夫特的API中的一个简单的方法来从数组中删除重复的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 21:40