Hello,
I want to check if the element 'Medic()' exists in my array.
`var array = [Medic(), AssaultSoldier(), Sniper()] `
Thank you all.
I want to check if the element 'Medic()' exists in my array.
`var array = [Medic(), AssaultSoldier(), Sniper()] `
Thank you all.
Swift’s standard library includes a wealth of algorithms that you can reuse and thus make your code simpler and smaller. For example:
The contains(where:) method returns true if the supplied closure return true for any item in the collection, while the firstIndex(where:) returns the index of that item.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
Code Block class Soldier { } class Medic: Soldier { } class AssaultSoldier: Soldier { } class Sniper: Soldier { } let array = [Medic(), AssaultSoldier(), Sniper()] let containsMedic = array.contains(where: { $0 is Medic }) print(containsMedic) // true let indexOfFirstMedic = array.firstIndex(where: { $0 is Medic }) print(indexOfFirstMedic) // Optional(0)
The contains(where:) method returns true if the supplied closure return true for any item in the collection, while the firstIndex(where:) returns the index of that item.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"