How to check if an element is in an array

后端 未结 17 1114
囚心锁ツ
囚心锁ツ 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 10:49

    what about using a hash table for the job, like this?

    first, creating a "hash map" generic function, extending the Sequence protocol.

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

    This extension will work as long as the items in the array conform to Hashable, like integers or strings, here is the usage...

    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
    

    But for now, let's just focus in check if the element is in the array.

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

提交回复
热议问题