Alexey K Alexey K -4 years ago 85
Swift Question

How to iterate through array of objects in Swift?

i have objects

var person1 = Person() = "Joe"
person1.lastName = "Doe"
person1.age = 21

var person2 = Person() = "Julia"
person2.lastName = "Ivanova"
person2.age = 22

var person3 = Person() = "Irina"
person3.lastName = "Petrova"
person3.age = 25

var person9 = Person() = "Vova"
person9.lastName = "Vovin"
person9.age = 32

var person10 = Person() = "Masha"
person10.lastName = "Golovanova"
person10.age = 20

var person11 = Person() = "Petra"
person11.lastName = "Andreeva"
person11.age = 27

and multi array

var array = [[person1, person2, person3], [person9, person10, person11]]

how can I iterate through array to get for example a person with name="Masha"

thanks in advance

Answer Source

I would try this:

var array:[[Person]] = [[person1, person2, person3], [person9, person10, person11]]
/*Casting it like this should keep from getting an error later 
   and/or having to recast the objects*/

for people in array {

/*This is going to look at each array in arrays, 
   and call each one 'people' within this loop*/

    for person in people {

    /*Same thing, this is going to look at each item in the people array
       and call each one 'person' within this loop*/

        if == "Masha" {
            return person
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download