How to check if an element is in an array

后端 未结 17 967
囚心锁ツ
囚心锁ツ 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:57

    Use this extension:

    extension Array {
        func contains(obj: T) -> Bool {
            return self.filter({$0 as? T == obj}).count > 0
        }
    }
    

    Use as:

    array.contains(1)
    

    Updated for Swift 2/3

    Note that as of Swift 3 (or even 2), the extension is no longer necessary as the global contains function has been made into a pair of extension method on Array, which allow you to do either of:

    let a = [ 1, 2, 3, 4 ]
    
    a.contains(2)           // => true, only usable if Element : Equatable
    
    a.contains { $0 < 1 }   // => false
    

提交回复
热议问题