0

In Swift, if I want to check to see if an object (one that is more complex than a string exists) within an array, how do I do that? Answers found on pages like this (How to check if an element is in an array) don't seem to work in my case.

For example, if I had an object class of Dogs, where each dog had multiple properties (like weight, color, breed, etc.)... and I created several instances of that class and appended them to a single array... how could I then check to see if a certain object was in that array?

if singleDogInstance is in arrayOfDogs {
    //do something
}
Community
  • 1
  • 1

1 Answers1

1

You can use the contains function from the Swift library as long as the elements contained in the array conform to the Equitable protocol, which basically requires that you create a global == operation that compares two instances of your class.

struct Dog: Equatable {
    let name: String
}

func ==( lhs: Dog, rhs: Dog ) -> Bool {
    return lhs.name == rhs.name
}

let arrayOfDogs = [ Dog( name:"Panzer" ), Dog( name:"Bentley" ), Dog( name:"Ewok" ) ]
let singleDogInstance = arrayOfDogs[0]
print( contains( arrayOfDogs, singleDogInstance ) ) // True

let someOtherDog = Dog( name:"Oliver" )
print( contains( arrayOfDogs, singleDogInstance ) ) // False

And of course, in Swift 2.0 the contains function is no longer global but part of Array:

arrayOfDogs.contains( singleDogInstance )
Patrick Lynch
  • 2,742
  • 1
  • 16
  • 18