识别数组

时间:2016-09-12 21:49:30

标签: arrays swift swift2

我有一组自定义对象,想要知道如何识别哪些对象是重复的。我知道如何删除重复项,但这不是我之后的功能。我正在使用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"]

所以我想显示一个包含上面电影列表的表格视图,但是用#34;蝙蝠侠"和#34; Deadpool"突出显示。

为了更清楚地了解我想要实现的内容,请查看屏幕截图。我有一个两个用户在以前的视图控制器中选择的电影列表。我想在表格视图中显示所选的电影。我想特别展示是否有人都选择了电影。

enter image description here

4 个答案:

答案 0 :(得分:4)

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

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")
}

答案 1 :(得分:3)

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

解决方案使用与接受的答案相同的技术,但是采用更通用的形式(紧凑而subscript扩展到Dictionary):freq() dictionary extension来自{{3} (GitHub user oisdk's excellent SwiftSequence framework):

/* ---------------------------------------------------------------------------
   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]

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

答案 2 :(得分:0)

为什么不在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)
        }
    }

答案 3 :(得分:0)

不确定要制作哪些功能。

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

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