Removing duplicate elements from an array in Swift

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

    Slightly more succinct syntax version of Daniel Krom's Swift 2 answer, using a trailing closure and shorthand argument name, which appears to be based on Airspeed Velocity's original answer:

    func uniq(source: S) -> [E] {
      var seen = [E: Bool]()
      return source.filter { seen.updateValue(true, forKey: $0) == nil }
    }
    

    Example of implementing a custom type that can be used with uniq(_:) (which must conform to Hashable, and thus Equatable, because Hashable extends Equatable):

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

    In the above code...

    id, as used in the overload of ==, could be any Equatable type (or method that returns an Equatable type, e.g., someMethodThatReturnsAnEquatableType()). The commented-out code demonstrates extending the check for equality, where someOtherEquatableProperty is another property of an Equatable type (but could also be a method that returns an Equatable type).

    id, as used in the hashValue computed property (required to conform to Hashable), could be any Hashable (and thus Equatable) property (or method that returns a Hashable type).

    Example of using uniq(_:):

    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
    

提交回复
热议问题