Swift: didNotContain method for array

I'm familiar with the function contains(array, object)

, but I need a "does not contain" function. I can't think of any logic to get around this, so I could use some help!

My code is currently the exact opposite of what I need. This is only adding objects that are contained in array

; I want to add every object that is not in array

.

The code is here:

var array = ["Ben", "Jessica", "Cody", "Katie", "Jacob"]
if array.contains("Ben") {
    print("Contains Ben")
}

      

+3


source to share


3 answers


I feel dumb.



!contains(array, "Ben")

      

+5


source


You can also write an extension on Array

extension Array {
    func doesNotContain <T: Equatable> (items: T...) -> Bool {
        return !contains(items)
    }
}

      



Now you can use it like yourArray.doesNotContain(item1, item2, item 3)

.

+1


source


The command ".contains (element)" returns Bool, which means these 2 statements give the same result

if array.contains("Ben") { code }
if array.contains("Ben") == true { code }

      

therefore

if array.contains("Ben") == false { code }

      

Will execute code if array does not contain value

0


source







All Articles