Removing duplicate elements from an array in Swift

后端 未结 30 2528
遥遥无期
遥遥无期 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:55

    Here is a solution that

    • Uses no legacy NS types
    • Is reasonably fast with O(n)
    • Is concise
    • Preserves element order
    extension Array where Element: Hashable {
    
        var uniqueValues: [Element] {
            var allowed = Set(self)
            return compactMap { allowed.remove($0) }
        }
    }
    

提交回复
热议问题