Remove duplicates from array comparing the properties of its objects

前端 未结 6 1291
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 03:50

Suppose I have a class Event, and it has 2 properties: action (NSString) and date (NSDate).

And suppose I have an array of Event objects. The problem is that \"date\" pr

6条回答
  •  借酒劲吻你
    2021-02-04 04:22

    Here is a Swift extension on the NSArray class that removes duplicates for the specified property:

    extension NSArray {
    /**
     - parameter property: the name of the property to check for duplicates
    
     - returns: an array of objects without objects that share an identical value of the specified property
    */
      func arrayWithoutObjectsOfDuplicateProperty(property : String) -> [AnyObject] {
        var seenInstances = NSMutableSet()
    
        let predicate = NSPredicate { (obj, bind) -> Bool in
          let seen = seenInstances.containsObject(obj.valueForKey(property)!)
    
          if !seen {
            seenInstances.addObject(obj.valueForKey(property)!)
          }
            return !seen
          }      
          return self.filteredArrayUsingPredicate(predicate)
      }
    }
    

提交回复
热议问题