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

我需要的例子:

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

当前回答

数组

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

其他回答

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

你可以为Array添加一个扩展:

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

这可以用于:

if myArray.contains(myItem) {
   // code here
}

像这样使用哈希表如何?

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

如果您正在检查一个自定义类或结构的实例是否包含在数组中,那么在使用.contains(myObject)之前,您需要实现Equatable协议。

例如:

struct Cup: Equatable {
    let filled:Bool
}

static func ==(lhs:Cup, rhs:Cup) -> Bool { // Implement Equatable
    return lhs.filled == rhs.filled
}

然后你可以这样做:

cupArray.contains(myCup)

提示:==重写应该在全局级别,而不是在类/结构中