How to check if an element is in an array

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

    Swift 2, 3, 4, 5:

    let elements = [1, 2, 3, 4, 5]
    if elements.contains(5) {
        print("yes")
    }
    

    contains() is a protocol extension method of SequenceType (for sequences of Equatable elements) and not a global method as in earlier releases.

    Remarks:

    • This contains() method requires that the sequence elements adopt the Equatable protocol, compare e.g. Andrews's answer.
    • If the sequence elements are instances of a NSObject subclass then you have to override isEqual:, see NSObject subclass in Swift: hash vs hashValue, isEqual vs ==.
    • There is another – more general – contains() method which does not require the elements to be equatable and takes a predicate as an argument, see e.g. Shorthand to test if an object exists in an array for Swift?.

    Swift older versions:

    let elements = [1,2,3,4,5]
    if contains(elements, 5) {
        println("yes")
    }
    

提交回复
热议问题