快速数组的唯一值

我正在构建一个 iOS 应用程序与迅速,我需要得到所有的字符串数组的唯一值。

我一直在阅读苹果开发者文档,但它似乎没有一个功能。

谁能给我点提示吗?

125687 次浏览

Use a dictionary like var unique = [<yourtype>:Bool]() and fill in the values like unique[<array value>] = true in a loop. Now unique.keys has what you need.

There isn't a function to do this in the Swift standard library, but you could write one:

extension Sequence where Iterator.Element: Hashable {
func unique() -> [Iterator.Element] {
var seen: [Iterator.Element: Bool] = [:]
return self.filter { seen.updateValue(true, forKey: $0) == nil }
}
}


let a = ["four","one", "two", "one", "three","four", "four"]
a.unique // ["four", "one", "two", "three"]

This has the downside of requiring the contents of the sequence to be hashable, not just equatable, but then again most equatable things are, including strings.

It also preserves the original ordering unlike, say, putting the contents in a dictionary or set and then getting them back out again.

There might be a more efficient way, but an extension would probably be most straightforward:

extension Array where Element: Equatable {
var unique: [Element] {
var uniqueValues: [Element] = []
forEach { item in
guard !uniqueValues.contains(item) else { return }
uniqueValues.append(item)
}
return uniqueValues
}
}

If order doesn't matter and objects are also hashable:

let array = ["one", "one", "two", "two", "three", "three"]
// order NOT guaranteed
let unique = Array(Set(array))
// ["three", "one", "two"]

I don't know of a built in way. This generic function would do it:

func distinct<S: SequenceType, E: Equatable where E==S.Generator.Element>(source: S) -> [E]
{
var unique = [E]()


for item in source
{
if !contains(unique, item)
{
unique.append(item)
}
}
return unique
}

The downside here is that this solution runs in O(n2).