How to check if an element is in an array

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

    Here is my little extension I just wrote to check if my delegate array contains a delegate object or not (Swift 2). :) It Also works with value types like a charm.

    extension Array
    {
        func containsObject(object: Any) -> Bool
        {
            if let anObject: AnyObject = object as? AnyObject
            {
                for obj in self
                {
                    if let anObj: AnyObject = obj as? AnyObject
                    {
                        if anObj === anObject { return true }
                    }
                }
            }
            return false
        }
    }
    

    If you have an idea how to optimize this code, than just let me know.

提交回复
热议问题