# 从数组中删除重复的元素

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

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

` `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]` `

` `let unique = Array(Set(originals))` `

` `extension Array where Element:Equatable { func removeDuplicates() -> [Element] { var result = [Element]() for value in self { if result.contains(value) == false { result.append(value) } } return result } }` `

` `let arrayOfInts = [2, 2, 4, 4] print(arrayOfInts.removeDuplicates()) // Prints: [2, 4]` `

` `extension Array { func filterDuplicates(@noescape includeElement: (lhs:Element, rhs:Element) -> Bool) -> [Element]{ var results = [Element]() forEach { (element) in let existingElements = results.filter { return includeElement(lhs: element, rhs: \$0) } if existingElements.count == 0 { results.append(element) } } return results } }` `

` `let filteredElements = myElements.filterDuplicates { \$0.PropertyOne == \$1.PropertyOne && \$0.PropertyTwo == \$1.PropertyTwo }` `

Swift 3

` `public extension Sequence where Iterator.Element: Hashable { var uniqueElements: [Iterator.Element] { return Array( Set(self) ) } } public extension Sequence where Iterator.Element: Equatable { var uniqueElements: [Iterator.Element] { return self.reduce([]){ uniqueElements, element in uniqueElements.contains(element) ? uniqueElements : uniqueElements + [element] } } }` `

Swift 2

` `public extension SequenceType where Generator.Element: Hashable { var uniqueElements: [Generator.Element] { return Array( Set(self) ) } } public extension SequenceType where Generator.Element: Equatable { var uniqueElements: [Generator.Element] { return self.reduce([]){uniqueElements, element in uniqueElements.contains(element) ? uniqueElements : uniqueElements + [element] } } }` `

` `extension Array where Element: Equatable { var orderedSet: Array { var array: [Element] = [] return flatMap { if array.contains(\$0) { return nil } else { array.append(\$0) return \$0 } } } }` `

` `extension Array where Element: Hashable { var orderedSet: Array { var set = Set<Element>() return flatMap { set.insert(\$0).inserted ? \$0 : nil } } }` `

` `extension Array where Element: Hashable { var orderedSet: Array { var set = Set<Element>() return filter { set.insert(\$0).inserted } } }` `

` `extension Array where Element: Hashable { var orderedSet: Array { return NSOrderedSet(array: self).array as? Array ?? [] } }` `

` `let integers = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6] let integersOrderedSet = integers.orderedSet // [1, 4, 2, 6, 24, 15, 60]` `

` `func deleteDuplicates<S: ExtensibleCollectionType where S.Generator.Element: Equatable>(seq:S)-> S { let s = reduce(seq, S()){ ac, x in contains(ac,x) ? ac : ac + [x] } return s }` `

# 迅速2

uniq功能回答：

` `func uniq<S: SequenceType, E: Hashable where E==S.Generator.Element>(source: S) -> [E] { var seen: [E:Bool] = [:] return source.filter({ (v) -> Bool in return seen.updateValue(true, forKey: v) == nil }) }` `

` `var test = [1,2,3,4,5,6,7,8,9,9,9,9,9,9] print(uniq(test)) //1,2,3,4,5,6,7,8,9` `

Swift 3.0

` `let uniqueUnordered = Array(Set(array)) let uniqueOrdered = Array(NSOrderedSet(array: array))` `

` `public extension Sequence where Iterator.Element: Hashable { public func unique() -> [Iterator.Element] { var buffer: [Iterator.Element] = [] var lookup = Set<Iterator.Element>() for element in self { guard !lookup.contains(element) else { continue } buffer.append(element) lookup.insert(element) } return buffer } }` `

` `public extension Sequence where Iterator.Element: Equatable { public func unique() -> [Iterator.Element] { var buffer: [Iterator.Element] = [] for element in self { guard !buffer.contains(element) else { continue } buffer.append(element) } return buffer } }` `

` `var myArray = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6] var mySet = Set<Int>(myArray) myArray = Array(mySet) // [2, 4, 60, 6, 15, 24, 1]` `

` `myArray.sort{\$0 < \$1} // [1, 2, 4, 6, 15, 24, 60]` `

Daniel Krom的Swift 2答案稍微简洁一些，使用了一个尾随的闭包和速记参数名，这个名字看起来是基于Airspeed Velocity的原始答案的 ：

` `func uniq<S: SequenceType, E: Hashable where E == S.Generator.Element>(source: S) -> [E] { var seen = [E: Bool]() return source.filter { seen.updateValue(true, forKey: \$0) == nil } }` `

` `func ==(lhs: SomeCustomType, rhs: SomeCustomType) -> Bool { return lhs.id == rhs.id // && lhs.someOtherEquatableProperty == rhs.someOtherEquatableProperty } struct SomeCustomType { let id: Int // ... } extension SomeCustomType: Hashable { var hashValue: Int { return id } }` `

`==`的重载中使用的`id`可以是任何的`Equatable`类型（或返回`Equatable`类型的方法，例如`someMethodThatReturnsAnEquatableType()` ）。 注释代码演示如何扩展相等检查，其中`someOtherEquatableProperty``Equatable`类型的另一个属性（但也可以是返回`Equatable`类型的方法）。

`hashValue`计算属性（要求符合`Hashable` ）中使用的`id`可以是任何`Hashable` （也`Equatable` ）属性（或返回`Hashable`类型的方法）。

` `var someCustomTypes = [SomeCustomType(id: 1), SomeCustomType(id: 2), SomeCustomType(id: 3), SomeCustomType(id: 1)] print(someCustomTypes.count) // 4 someCustomTypes = uniq(someCustomTypes) print(someCustomTypes.count) // 3` `

• 保留输入数组中元素的顺序
• 线性复杂度O（n）：单通滤波器O（n）+集合插入O（1）

` `let numberArray = [10, 1, 2, 3, 2, 1, 15, 4, 5, 6, 7, 3, 2, 12, 2, 5, 5, 6, 10, 7, 8, 3, 3, 45, 5, 15, 6, 7, 8, 7]` `

` `func orderedSet<T: Hashable>(array: Array<T>) -> Array<T> { var unique = Set<T>() return array.filter { element in return unique.insert(element).inserted } } orderedSet(array: numberArray) // [10, 1, 2, 3, 15, 4, 5, 6, 7, 12, 8, 45]` `

` `extension Array where Element:Hashable { var orderedSet: Array { var unique = Set<Element>() return filter { element in return unique.insert(element).inserted } } } numberArray.orderedSet // [10, 1, 2, 3, 15, 4, 5, 6, 7, 12, 8, 45]` `

` `var arrayOfDates: NSArray = ["15/04/01","15/04/01","15/04/02","15/04/02","15/04/03","15/04/03","15/04/03"] var datesOnlyDict = NSMutableDictionary() var x = Int() for (x=0;x<(arrayOfDates.count);x++) { let date = arrayOfDates[x] as String datesOnlyDict.setValue("foo", forKey: date) } let uniqueDatesArray: NSArray = datesOnlyDict.allKeys // uniqueDatesArray = ["15/04/01", "15/04/03", "15/04/02"] println(uniqueDatesArray.count) // = 3` `

` `var sortedArray = sorted(datesOnlyArray) { (obj1, obj2) in let p1 = obj1 as String let p2 = obj2 as String return p1 < p2 } println(sortedArray) // = ["15/04/01", "15/04/02", "15/04/03"]` `

` `/// Extensions for performing set-like operations on lists, maintaining order extension Array where Element: Hashable { func unique() -> [Element] { var seen: [Element:Bool] = [:] return self.filter({ seen.updateValue(true, forKey: \$0) == nil }) } func subtract(takeAway: [Element]) -> [Element] { let set = Set(takeAway) return self.filter({ !set.contains(\$0) }) } func intersect(with: [Element]) -> [Element] { let set = Set(with) return self.filter({ set.contains(\$0) }) } }` `

` `// Custom Struct. Can be also class. // Need to be `equitable` in order to use `contains` method below struct CustomStruct : Equatable { let name: String let lastName : String } // conform to Equatable protocol. feel free to change the logic of "equality" func ==(lhs: CustomStruct, rhs: CustomStruct) -> Bool { return (lhs.name == rhs.name && lhs.lastName == rhs.lastName) } let categories = [CustomStruct(name: "name1", lastName: "lastName1"), CustomStruct(name: "name2", lastName: "lastName1"), CustomStruct(name: "name1", lastName: "lastName1")] print(categories.count) // prints 3 // remove duplicates (and keep initial order of elements) let uniq1 : [CustomStruct] = categories.reduce([]) { \$0.contains(\$1) ? \$0 : \$0 + [\$1] } print(uniq1.count) // prints 2 - third element has removed` `

` `let uniq2 : [CustomStruct] = categories.reduce([]) { (result, category) in var newResult = result if (newResult.contains(category)) {} else { newResult.append(category) } return newResult } uniq2.count // prints 2 - third element has removed` `

` `extension Array where Element: Equatable { /// Array containing only _unique_ elements. var unique: [Element] { var result: [Element] = [] for element in self { if !result.contains(element) { result.append(element) } } return result } }` `

` `extension Array { func filterDuplicate<T>(_ keyValue:(Element)->T) -> [Element] { var uniqueKeys = Set<String>() return filter{uniqueKeys.insert("\(keyValue(\$0))").inserted} } } // example usage: (for a unique combination of attributes): peopleArray = peopleArray.filterDuplicate{ (\$0.name, \$0.age, \$0.sex) }` `

` `let initialArray = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6] let distinct2 = initialArray.reduce(Set<Int>(), combine: { (set, current) -> Set<Int> in var tmp = set tmp.insert(current) return tmp }) // distinct2 is now a set containing {2, 4, 60, 6, 15, 24, 1} // Make it into a sorted array let sorted = Array(distinct2).sorted(<) // Returns [1, 2, 4, 6, 15, 24, 60]` `

` `struct DistinctWrapper <T>: Hashable { var underlyingObject: T var distinctAttribute: String var hashValue: Int { return distinctAttribute.hashValue } } func distinct<S : SequenceType, T where S.Generator.Element == T>(source: S, distinctAttribute: (T) -> String, resolution: (T, T) -> T) -> [T] { let wrappers: [DistinctWrapper<T>] = source.map({ return DistinctWrapper(underlyingObject: \$0, distinctAttribute: distinctAttribute(\$0)) }) var added = Set<DistinctWrapper<T>>() for wrapper in wrappers { if let indexOfExisting = added.indexOf(wrapper) { let old = added[indexOfExisting] let winner = resolution(old.underlyingObject, wrapper.underlyingObject) added.insert(DistinctWrapper(underlyingObject: winner, distinctAttribute: distinctAttribute(winner))) } else { added.insert(wrapper) } } return Array(added).map( { return \$0.underlyingObject } ) } func == <T>(lhs: DistinctWrapper<T>, rhs: DistinctWrapper<T>) -> Bool { return lhs.hashValue == rhs.hashValue } // tests // case : perhaps we want to get distinct addressbook list which may contain duplicated contacts like Irma and Irma Burgess with same phone numbers // solution : definitely we want to exclude Irma and keep Irma Burgess class Person { var name: String var phoneNumber: String init(_ name: String, _ phoneNumber: String) { self.name = name self.phoneNumber = phoneNumber } } let persons: [Person] = [Person("Irma Burgess", "11-22-33"), Person("Lester Davidson", "44-66-22"), Person("Irma", "11-22-33")] let distinctPersons = distinct(persons, distinctAttribute: { (person: Person) -> String in return person.phoneNumber }, resolution: { (p1, p2) -> Person in return p1.name.characters.count > p2.name.characters.count ? p1 : p2 } ) // distinctPersons contains ("Irma Burgess", "11-22-33") and ("Lester Davidson", "44-66-22")` `

` `extension Array where Element: Equatable { public func uniq() -> [Element] { var arrayCopy = self arrayCopy.uniqInPlace() return arrayCopy } mutating public func uniqInPlace() { var seen = [Element]() var index = 0 for element in self { if seen.contains(element) { removeAtIndex(index) } else { seen.append(element) index++ } } } }` `

` `var numbers = [1, 6, 2, 2, 4, 1, 5] numbers.uniqInPlace() // array is now [1, 6, 2, 4, 5] let strings = ["Y", "Z", "A", "Y", "B", "Y", "Z"] let uniqStrings = strings.uniq() // uniqStrings is now ["Y", "Z", "A", "B"]` `

Swift 3

` `func uniq<S : Sequence, T : Hashable where S.Iterator.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(source: vals) // [1, 4, 2, 6, 24, 15, 60]` `

` `extension Array where Element:Hashable { var unique: [Element] { var set = Set<Element>() //the unique list kept in a Set for fast retrieval var arrayOrdered = [Element]() //keeping the unique list of elements but ordered for value in self { if !set.contains(value) { set.insert(value) arrayOrdered.append(value) } } return arrayOrdered } }` `
` `func removeDublicate (ab: [Int]) -> [Int] { var answer1:[Int] = [] for i in ab { if !answer1.contains(i) { answer1.append(i) }} return answer1 }` `

` `let f = removeDublicate(ab: [1,2,2]) print(f)` `

` `public extension Array where Element: Hashable { func uniqued() -> [Element] { var seen = Set<Element>() return filter{ seen.insert(\$0).inserted } } }` `
1. 转换为设置
2. 检查元素数是否等于之前的数组
3. 如果没有，则从Set创建Array

（使用Swift 3）

` ` var top3score: [Int] = [] outerLoop: for i in 0..<top10score.count { dlog(message: String(top10score[i])) if top3score.count == 3 { break } for aTop3score in top3score { if aTop3score == top10score[i] { continue outerLoop } } top3score.append(top10score[i]) } print("top10score is \(top10score)") //[14, 5, 5, 5, 3, 3, 2, 2, 2, 2] print("top3score is \(top3score)") //[14, 5, 3]` `

Swift 3.0

` `extension Array where Element: Equatable { func withoutDuplicates() -> [Element] { return self.reduce([], { (objects, object) -> [Element] in var objects = objects if !objects.contains(object) { objects.append(object) } return objects }) } }` `