How to check if an element is in an array

后端 未结 17 946
囚心锁ツ
囚心锁ツ 2020-11-22 10:24

In Swift, how can I check if an element exists in an array? Xcode does not have any suggestions for contain, include, or has, and a qu

相关标签:
17条回答
  • 2020-11-22 11:06

    Array

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

    Check elements presence

    elements.contains(5) // true
    

    Get elements index

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

    Get element count

    let results = elements.filter { element in element == 5 }
    results.count // 2
    
    0 讨论(0)
  • 2020-11-22 11:07

    if user find particular array elements then use below code same as integer value.

    var arrelemnts = ["sachin", "test", "test1", "test3"]
    
     if arrelemnts.contains("test"){
        print("found")   }else{
        print("not found")   }
    
    0 讨论(0)
  • 2020-11-22 11:09

    The simplest way to accomplish this is to use filter on the array.

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

    result will have the found element if it exists and will be empty if the element does not exist. So simply checking if result is empty will tell you whether the element exists in the array. I would use the following:

    if result.isEmpty {
        // element does not exist in array
    } else {
        // element exists
    }
    
    0 讨论(0)
  • 2020-11-22 11:10

    As of Swift 2.1 NSArrays have containsObjectthat can be used like so:

    if myArray.containsObject(objectImCheckingFor){
        //myArray has the objectImCheckingFor
    }
    
    0 讨论(0)
  • 2020-11-22 11:11

    Swift 4.2 +
    You can easily verify your instance is an array or not by the following function.

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

    Even you can access it as follows. You will receive nil if the object wouldn't be an array.

    func verifyIsObjectOfAnArray<T>(_ object: T) -> [T]? {
       if let array = object as? [T] {
          return array
       }
    
       return nil
    }
    
    0 讨论(0)
提交回复
热议问题