Xcode Swift check if array contains object

匿名 (未验证) 提交于 2019-12-03 07:36:14

问题:

I have this array :

  var preferiti : [ModalHomeLine!] = [] 

I want to check if the array contains the same object.

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

回答1:

So it sounds like you want an array without duplicate objects. In cases like this, a set is what you want. Surprisingly, Swift doesn't have a set, so you can either create your own or use NSSet, which would look something like this:

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. 

UPDATE:

Swift 1.2 added a set type! Now you can do something like

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. 


回答2:

Swift has a generic contains function:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!