在[AnyObject] Swift中删除重复项的有效方法

时间:2015-02-08 06:47:58

标签: objective-c swift

我有一个快速的[AnyObject]数组。某些对象具有相同的RestaurantName。什么是删除重复项并保持最高Votes

的最佳(资源最少)资源密集方式

注意:只有objectId中的RestaurantName相同,但每个都有一个唯一的ID。

AnyObject数组

Optional([<FoodPhoto: 0x1741088b0, objectId: FNJjZHxOvg, localId: (null)> {
    PhotoName = Test1;
    PhotoUploaded = "<PFFile: 0x170460b00>";
    RestaurantName = "<Restaurant: 0x17010a4d0, objectId: 0aKFrpKN46>";
    UserUploaded = "<PFUser: 0x1703627c0, objectId: wNJPsJDV6t>";
    Votes = 2;
}, <FoodPhoto: 0x17410ab90, objectId: yhiMZ3dkHR, localId: (null)> {
    PhotoName = Title1;
    PhotoUploaded = "<PFFile: 0x170460c00>";
    RestaurantName = "<Restaurant: 0x17010a7a0, objectId: 0aKFrpKN46>";
    UserUploaded = "<PFUser: 0x170362580, objectId: Zk56DgHGhi>";
    Votes = 5;
}, <FoodPhoto: 0x17410ab00, objectId: UNTRadeMjg, localId: (null)> {
    PhotoName = title2;
    PhotoUploaded = "<PFFile: 0x170460cc0>";
    RestaurantName = "<Restaurant: 0x17010a8c0, objectId: 0aKFrpKN46>";
    UserUploaded = "<PFUser: 0x170362340, objectId: Zk56DgHGhi>";
    Votes = 0;
}, <FoodPhoto: 0x17410ac20, objectId: 7C8voifUHd, localId: (null)> {
    PhotoName = title3;
    PhotoUploaded = "<PFFile: 0x170460d80>";
    RestaurantName = "<Restaurant: 0x17010a9e0, objectId: 0aKFrpKN46>";
    UserUploaded = "<PFUser: 0x1703624c0, objectId: Zk56DgHGhi>";
    Votes = 0;
}])

1 个答案:

答案 0 :(得分:2)

如果顺序不重要,我要做的是创建一个由objectId键入的hashmap,如下所示:

var hashtable = [String: FoodPhoto]()
for foodPhoto in photos {
    let oldFoodPhoto = hashtable[foodPhoto.objectId]
    if oldFoodPhoto == nil || oldFoodPhoto!.Votes < foodPhoto.Votes {
        hashtable[foodPhoto.objectId] = foodPhoto
    }
}

然后hashtable.values将拥有所有唯一的FoodPhoto。