Checking if object is not of type in swift

Using swift syntax this is one way to do this

let animals: [Animals] = [Horse(), Cat(), Dog(), Spider()]
var chosenAnimals = animals.filter { type(of: $0) != Spider.self }

alternatively

var chosenAnimals = animals.filter { !($0 is Spider) }

Or, you can create your own isNot function, like this:

extension Animal {
    func isNot<T: Animal>(_ type: T.Type) -> Bool {
        return !(self is T)
    }
}

print(Horse().isNot(Fish.self)) // prints true
print(Horse().isNot(Horse.self)) // prints false

Tags:

Ios

Iphone

Swift