2016-11-17 37 views
1

我有叫Place自定義類3個屬性斯威夫特陣列特性:檢查複製

  • 名稱(String
  • 類別(String
  • 的GeoPoint(CLLocationCoordinate2D

我有一個包含100個對象的[Place]類型的數組,我想檢查GeoPoint屬性是否有重複項(就在這一個)。

如何在自定義對象數組中檢查特定屬性的重複項?

謝謝!

+2

的可能的複製[查找重複的元素在陣列使用夫特(http://stackoverflow.com/questions/29727618/find-duplicate-元素在數組使用swift) –

+0

你可以遍歷數組,爲每個GeoPoint創建一個字典,其中GeoPoint是關鍵,計數是值,然後檢查所有的值,看看是否有一個大於零。 – WMios

+0

@WMios我不會低估 –

回答

1

你可以做這樣的事情:

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。然後檢查是否有不止一次。

2

雖然接受的答案是好的,我想湊錢。

有兩個方法來達到你想要什麼,他們都通過SDK提供的功能效益。

1 - 使用Set s作爲評論中提到的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世界,但我覺得它是一個有用的工具。爲了達到這個目的,你需要從NSObject繼承Place。然後得到的獨特的地方的陣列可以減少到這一行:

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