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

我需要的例子:

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

当前回答

像这样使用哈希表如何?

首先,创建一个“哈希映射”泛型函数,扩展Sequence协议。

extension Sequence where Element: Hashable {

    func hashMap() -> [Element: Int] {
        var dict: [Element: Int] = [:]
        for (i, value) in self.enumerated() {
            dict[value] = i
        }
        return dict
    }
}

这个扩展将工作,只要数组中的项目符合Hashable,像整数或字符串,这里是用法…

let numbers = Array(0...50) 
let hashMappedNumbers = numbers.hashMap()

let numToDetect = 35

let indexOfnumToDetect = hashMappedNumbers[numToDetect] // returns the index of the item and if all the elements in the array are different, it will work to get the index of the object!

print(indexOfnumToDetect) // prints 35

但现在,我们只检查元素是否在数组中。

let numExists = indexOfnumToDetect != nil // if the key does not exist 
means the number is not contained in the collection.

print(numExists) // prints true

其他回答

以防有人试图找到一个indexPath是否在选定的(如在UICollectionView或UITableView cellForItemAtIndexPath函数):

    var isSelectedItem = false
    if let selectedIndexPaths = collectionView.indexPathsForSelectedItems() as? [NSIndexPath]{
        if contains(selectedIndexPaths, indexPath) {
            isSelectedItem = true
        }
    }

为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)

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

斯威夫特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)
}

Swift 2、3、4、5:

let elements = [1, 2, 3, 4, 5]
if elements.contains(5) {
    print("yes")
}

contains()是SequenceType的一个协议扩展方法(用于Equatable元素的序列),而不是一个全局方法 早些时候发布。

备注:

此contains()方法要求序列元素 采用平等协议,比较例如安德鲁斯的答案。 如果序列元素是NSObject子类的实例 那么你必须重写isEqual:,参见Swift中的NSObject子类:hash vs hashValue, isEqual vs ==。 还有另一种更通用的contains()方法,它不要求元素相等,并将谓词作为 参数,参见例如:测试Swift?数组中是否存在对象的简写。

Swift旧版本:

let elements = [1,2,3,4,5]
if contains(elements, 5) {
    println("yes")
}

数组

let elements = [1, 2, 3, 4, 5, 5]

检查元素是否存在

elements.contains(5) // true

获取元素索引

elements.firstIndex(of: 5) // 4
elements.firstIndex(of: 10) // nil

获取元素计数

let results = elements.filter { element in element == 5 }
results.count // 2