在Swift中,我如何检查数组中是否存在一个元素?Xcode并没有给出包含、包含或拥有的建议,快速搜索这本书也一无所获。知道怎么检查这个吗?我知道有一个方法找到返回索引号,但是否有一个方法返回一个布尔像ruby的#include??

我需要的例子:

var elements = [1,2,3,4,5]
if elements.contains(5) {
  //do something
}

当前回答

对于那些来这里寻找从数组中查找并移除对象的人:

斯威夫特1

if let index = find(itemList, item) {
    itemList.removeAtIndex(index)
}

斯威夫特2

if let index = itemList.indexOf(item) {
    itemList.removeAtIndex(index)
}

Swift 3,4

if let index = itemList.index(of: item) {
    itemList.remove(at: index)
}

斯威夫特5.2

if let index = itemList.firstIndex(of: item) {
    itemList.remove(at: index)
}

其他回答

斯威夫特

如果你不使用object,那么你可以使用此代码用于contains。

let elements = [ 10, 20, 30, 40, 50]

if elements.contains(50) {

   print("true")

}

如果你在swift中使用NSObject类。这个变量符合我的要求。您可以根据自己的需求进行修改。

var cliectScreenList = [ATModelLeadInfo]()
var cliectScreenSelectedObject: ATModelLeadInfo!

这是针对相同的数据类型。

{ $0.user_id == cliectScreenSelectedObject.user_id }

如果你想要AnyObject类型。

{ "\($0.user_id)" == "\(cliectScreenSelectedObject.user_id)" }

已满的状况

if cliectScreenSelected.contains( { $0.user_id == cliectScreenSelectedObject.user_id } ) == false {

    cliectScreenSelected.append(cliectScreenSelectedObject)

    print("Object Added")

} else {

    print("Object already exists")

 }

Swift 4.2 + 通过下面的函数,可以很容易地验证实例是否是数组。

func verifyIsObjectOfAnArray<T>(_ object: T) -> Bool {
   if let _ = object as? [T] {
      return true
   }

   return false
}

甚至你也可以像下面这样访问它。如果对象不是数组,你将收到nil。

func verifyIsObjectOfAnArray<T>(_ object: T) -> [T]? {
   if let array = object as? [T] {
      return array
   }

   return nil
}

我用滤镜。

let results = elements.filter { el in el == 5 }
if results.count > 0 {
    // any matching items are in results
} else {
    // not found
}

如果你愿意,你可以把它压缩成

if elements.filter({ el in el == 5 }).count > 0 {
}

希望这能有所帮助。


Swift 2更新

为默认实现欢呼!

if elements.contains(5) {
    // any matching items are in results
} else {
    // not found
}

最简单的方法是在数组上使用过滤器。

let result = elements.filter { $0==5 }

如果元素存在,结果将显示已找到的元素;如果元素不存在,结果将为空。因此,简单地检查result是否为空将告诉您元素是否存在于数组中。我会使用以下方法:

if result.isEmpty {
    // element does not exist in array
} else {
    // element exists
}

为Swift 2+更新

请注意,从Swift 3(甚至2)开始,下面的扩展不再需要,因为全局contains函数已经被做成了Array上的一对扩展方法,这允许你做以下任何一种:

let a = [ 1, 2, 3, 4 ]

a.contains(2)           // => true, only usable if Element : Equatable

a.contains { $0 < 1 }   // => false

Swift 1的历史答案:

使用这个扩展:(更新到Swift 5.2)

 extension Array {
     func contains<T>(obj: T) -> Bool where T: Equatable {
         return !self.filter({$0 as? T == obj}).isEmpty
     }
 }

使用:

array.contains(1)