0

I have an array with custom objects by 2 types. Also I have TableView, which shows objects from array. I need to select tableViewCell and check, if the element already in array - remove it from array, otherwise add it to array. I know, there is method for the checking array.contains(element) but my array looks like [Any] and it doesn't have this method.

I'm trying to check it with use for-in, but it's not good solution.

How can I do this?

let a: Int = 5
let b: String = "3"
let array: [Any] = [a, b]
trungduc
  • 11,926
  • 4
  • 31
  • 55
Sergey Hleb
  • 152
  • 1
  • 16

1 Answers1

2

You are able to cast Any to Int or String type and just use array.contains

array.contains {
    if let intValue = $0 as? Int {
        return intValue == 3
    } else if let stringValue = $0 as? String {
        return stringValue == "3"
    }
    return false
}

OR use this extension (Swift 4):

extension Array where Element: Any {
    func contains<T: Equatable>(_ element: T) -> Bool {
        return contains {
            guard let value = $0 as? T else { return false }
            return value == element
        }
    }
}


array.contains("3") // true for your example
Vlad Khambir
  • 4,313
  • 1
  • 17
  • 25