识别数组中的重复项

Identify Duplicates In Array

我有一组自定义对象,想知道如何识别哪些对象是重复的。我知道如何删除重复项,但这不是我想要的功能。我正在使用 swift 2.

示例:

var movies: [Movie] = ["Batman v Superman: Dawn of Justice", "Batman v Superman: Dawn of Justice", "Deadpool"," "Deadpool", "Hardcore Henry", "Jason Bourne", "Jurassic World"]

所以我想显示一个 table 视图,其中包含上面的电影列表,但 "Batman" 和 "Deadpool" 突出显示。

要更清楚地了解我要实现的目标,请查看屏幕截图。我有一个电影列表,两个用户 select 在以前的视图控制器中。我想在 table 视图中显示 selected 电影。我想特别说明一下是否有两个人 select 都看过的电影。

为什么不在 Movie 对象中添加一个 id

并比较搜索同一对象的两个数组。

public class Movie:Equatable{
    var id=NSUUID().UUIDString
}

public func ==(lhs: Movie, rhs: Movie) -> Bool{
    return lhs.id == rhs.id
}

比较数组:

    var moviesA=[Movie]()
    var moviesB=[Movie]()

    var sharedMovies=[Movie]()
    for movie in moviesA{
        if moviesB.contains(movie){
            sharedMovies.append(movie)
        }
    }

根据你的评论,我用字符串数组做了一个简单的例子,它可以很容易地转换成你的电影类型:

let movies = ["Batman","Batman","Flash","Avengers"]
var movieCounts:[String:Int] = [:]    
for movie in movies {
 movieCounts[movie] = (movieCounts[movie] ?? 0) + 1
}

你可以这样测试它:

for (key, value) in movieCounts {
 print("\(key) has been selected \(value) time/s")
}

不确定你想要实现什么功能。

如果仅用于项目列表,您可以使用 swift 字典来计算重复项,方法是使用电影名称作为键并作为从 0 开始的值计数。

如果要突出显示,可以在委托方法中填充 table 时使用不同的样式,方法是检查项目是否重复。

我通常尽量避免发布完全由其他人编写的代码的答案 (MIT License),但下面的参考非常适合这个问题,我认为它值得作为答案包括在内。


该解决方案使用与已接受答案相同的技术,但采用更通用的形式(通过对 Dictionary 的简洁 subscript 扩展变得紧凑):freq() 字典扩展 来自 GitHub 用户 oisdk 优秀的 SwiftSequence 框架 (MIT License):

/* ---------------------------------------------------------------------------
   source: GitHub user oisdk:
   https://github.com/oisdk/SwiftSequence/blob/master/Sources/Categorise.swift */
private extension Dictionary {
  subscript(key: Key, or or: Value) -> Value {
    get { return self[key] ?? or }
    set { self[key] = newValue }
  }
}

public extension SequenceType where Generator.Element : Hashable {
  // MARK: Frequencies

  /** 
  Returns a dictionary where the keys are the elements of self, and
  the values are their respective frequencies 
  ```swift
  [0, 3, 0, 1, 1, 3, 2, 3, 1, 0].freqs()
  // [2: 1, 0: 3, 3: 3, 1: 3]
  ```
  */
  @warn_unused_result
  func freqs() -> [Generator.Element:Int] {
    var freqs: [Generator.Element:Int] = [:]
    for el in self { freqs[el, or: 0] += 1 }
    return freqs
  }
}
/* --------------------------------------------------------------------------- */

/* example usage */
let movies = ["Batman","Batman","Flash","Avengers"]
print(movies.freqs()) // ["Avengers": 1, "Flash": 1, "Batman": 2]

查看许多其他序列好东西的框架: