Removing duplicate elements from an array in Swift

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

    I used @Jean-Philippe Pellet's answer and made an Array extension that does set-like operations on arrays, while maintaining the order of elements.

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

提交回复
热议问题