iOSGeek iOSGeek - 4 months ago 51
iOS Question

Check if an array contains all elements of another in Swift

I want to write an extension for array to check if an array contains all the elements of another array, in my use case it's string objects but I keep get:

Cannot convert value of type 'T.Generator.Element' to expected argument type '@noescape _ throws -> Bool'


in the line
self.contains(item)
the error in about
item


here is my code:

extension Array {
func containsArray<T : SequenceType where T.Generator.Element : Equatable> (array:T) -> Bool{
for item:T.Generator.Element in array{
if !self.contains(item) {
return false
}
}
return true
}
}

Answer

You have required that the sequence elements are Equatable, but they are unrelated to the array elements. Therefore

 if !self.contains(item) { ... }

does not compile.

What you probably want is to require that the sequence elements have the same type as the array elements (and that should be Equatable):

extension Array where Element: Equatable {
    func containsArray<T : SequenceType where T.Generator.Element == Element> (array:T) -> Bool {
        for item in array {
            if !self.contains(item) {
                return false
            }
        }
        return true
    }
}
Comments