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

我需要的例子:

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

当前回答

我用滤镜。

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
}

其他回答

像这样使用哈希表如何?

首先,创建一个“哈希映射”泛型函数,扩展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

斯威夫特4/5

实现这一点的另一种方法是使用过滤器函数

var elements = [1,2,3,4,5]
if let object = elements.filter({ $0 == 5 }).first {
    print("found")
} else {
    print("not found")
}

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

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

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

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

我用滤镜。

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
}

在Swift 2.1中,nsarray有containsobject,可以像这样使用:

if myArray.containsObject(objectImCheckingFor){
    //myArray has the objectImCheckingFor
}