【问题标题】:Check duplicates properties on Swift array检查 Swift 数组上的重复属性
【发布时间】:2016-11-17 07:54:13
【问题描述】:

我有一个名为 Place 的自定义类,它有 3 个属性:

  • 姓名 (String)
  • 类别 (String)
  • GeoPoint (CLLocationCoordinate2D)

我有一个包含 100 个对象的 [Place] 类型数组,我想检查 GeoPoint 属性上是否有重复项(仅在这个上)。

如何检查自定义对象数组中特定属性的重复项?

谢谢!

【问题讨论】:

  • 您可以遍历数组,为每个 GeoPoint 创建一个字典,其中 GeoPoint 为键,计数为值,然后检查所有值以查看是否有大于零的值。
  • @WMios 我不明白
  • 让它成为一个集合然后恢复到数组是我认为最快的方式
  • @FS.O6,如果您不理解我的评论,请参阅我的回答。

标签: ios iphone arrays swift cocoa-touch


【解决方案1】:

虽然接受的答案很好,但我想加入。

还有两种方法可以实现您想要的,它们都受益于 SDK 提供的功能。

1 - 使用Sets 作为评论中提到的 Tj3n。 要实现这一点,您需要使您的 Place 符合 Hashable 协议。

class Place : Hashable {
    var name = ""
    var category = ""
    var geoPoint: CLLocationCoordinate2D = CLLocationCoordinate2D()

    var hashValue: Int {
        get {
            return geoPoint.longitude.hashValue &+ geoPoint.latitude.hashValue
        }
    }
}

func ==(lhs: Place, rhs: Place) -> Bool {
    return lhs.geoPoint.latitude == rhs.geoPoint.latitude && lhs.geoPoint.longitude == rhs.geoPoint.longitude
}

hashValue 中的 &+ 运算符表示“添加,并且不会在溢出时崩溃”。使用它尽可能简单 - let set = Set(yourArrayOfPlaces) - set 将仅包含与 geoPoint 相关的唯一位置。

2 - 使用 KVC。虽然这更像是一个 Objective-C 世界,但我发现它是一个有用的工具。为此,您需要使Place 继承自NSObject。然后获得一系列独特的地方可以减少到这一行:

let uniquePlaces = (yourPlacesArray as NSArray).value(forKeyPath: "@distinctUnionOfObjects.geoPoint")

【讨论】:

    【解决方案2】:

    你可以这样做:

    var dict : [String : Int] = [:]
    
    for place in arr {
        if dict[place.GeoPoint] != nil {  // Not in dictionary
            if dict[place.GeoPoint] >= 1 { // If already there
                return true // Duplicate
            } else {
                dict[place.GeoPoint]! += 1 // Increment instance
            }
        } else {
            dict[place.GeoPoint] = 0 // Put in dictionary
        }
    }
    
    return false // No duplicates
    

    循环遍历[Place] 数组并检查有多少具有相同的GeoPoint。然后检查是否存在不止一次。

    【讨论】:

      猜你喜欢
      • 2016-10-25
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多