How to check if an element is in an array

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

    If you are checking if an instance of a custom class or struct is contained in an array, you'll need to implement the Equatable protocol before you can use .contains(myObject).

    For example:

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

    then you can do:

    cupArray.contains(myCup)
    

    Tip: The == override should be at the global level, not within your class/struct

提交回复
热议问题