Removing duplicate elements from an array in Swift

后端 未结 30 2014
遥遥无期
遥遥无期 2020-11-22 00:07

I might have an array that looks like the following:

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

Or, reall

30条回答
  •  天涯浪人
    2020-11-22 00:36

    Many answers available here, but I missed this simple extension, suitable for Swift 2 and up:

    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
        }
    }
    

    Makes it super simple. Can be called like this:

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

    Filtering based on properties

    To filter an array based on properties, you can use this method:

    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
        }
    }
    

    Which you can call as followed:

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

提交回复
热议问题