Xcode Swift 如何检查数组中是否包含某个对象

3

I have this array :

  var preferiti : [ModalHomeLine!] = []

我想检查数组是否包含相同的对象。
if the object exists {

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

1
你所指的“同一对象”是哪个对象?你想检查重复的对象吗? - oltman
如果 addPrf 存在,则执行 { },否则将 addPrf 添加到 preferiti 中。 - Massimiliano Allegretti
所以你有这样的东西:var myArray = [1, 2, 3],你想检查一个数字,比如说5是否存在? - Cesare
2个回答

8

Swift有一个通用的contains函数:

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

如何在我的情况下使用它? - Massimiliano Allegretti
@MassimilianoAllegretti,你的代码会说if !contains(perferiti, oggetto){ preferiti.append(addPrf) } - erdekhayser

5

听起来你想要一个没有重复对象的数组。在这种情况下,你需要使用一个set。令人惊讶的是,Swift没有一个set,所以你可以自己创建或使用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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接