Xcode Swift检查数组是否包含对象

时间:2015-02-19 19:40:32

标签: arrays swift

我有这个数组:

  var preferiti : [ModalHomeLine!] = []

我想检查数组是否包含相同的对象。

if the object exists {

} else {
  var addPrf = ModalHomeLine(titolo: nomeLinea, link: linkNumeroLinea, immagine : immagine, numero : titoloLinea)
  preferiti.append(addPrf)
}

2 个答案:

答案 0 :(得分:8)

Swift有一个通用contains函数:

contains([1,2,3,4],0) -> false
contains([1,2,3,4],3) -> true

答案 1 :(得分:5)

所以听起来你想要一个没有重复对象的数组。在这种情况下,set就是你想要的。令人惊讶的是,Swift没有一套,所以你可以自己创建或使用NSSet,看起来像这样:

let myset = NSMutableSet()
myset.addObject("a") // ["a"]
myset.addObject("b") // ["a", "b"]
myset.addObject("c") // ["a", "b", "c"]
myset.addObject("a") // ["a", "b", "c"] NOTE: this doesn't do anything because "a" is already in the set.

更新:

Swift 1.2添加了一套类型!现在你可以做类似

的事情了
let mySet = Set<String>()
mySet.insert("a") // ["a"]
mySet.insert("b") // ["a", "b"]
mySet.insert("c") // ["a", "b", "c"]
mySet.insert("a") // ["a", "b", "c"] NOTE: this doesn't do anything because "a" is already in the set.