Removing duplicate elements from an array in Swift

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

    Swift 4

    public extension Array where Element: Hashable {
        func uniqued() -> [Element] {
            var seen = Set()
            return filter{ seen.insert($0).inserted }
        }
    }
    

    every attempt to insert will also return a tuple: (inserted: Bool, memberAfterInsert: Set.Element). See documentation.

    Using the returned value helps us to avoid looping or doing any other operation.

提交回复
热议问题