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]
2

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

8 Comments

in example only 2 base classes, but in my code this is 4 or more custom classes
@SergeyHleb I have just added extension for array, use this extension for any your custom type.
let me few minutes, I check this
I'm trying your suggestion, but there is Use of unresolved identifier 'array'. I doing something stupid thing like: (_ element: T, array: [Any]), and in call it looks like: addingDevices.contains(device, array: addingDevices), but it works perfect, thank you.
Replace array.contains with self.contains in extension. Otherwise no benefit in making of extension.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.