How to iterate through array of objects in Swift?

后端 未结 6 811
慢半拍i
慢半拍i 2021-02-01 02:24

i have objects

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

var person2 = Person()
person2.name = \"Julia\"
person2         


        
6条回答
  •  再見小時候
    2021-02-01 03:16

    An interesting way of solving this would be to leverage the flatMap function of Swift.

    var array = [[person1, person2, person3], [person9, person10, person11]]
    
    let flatArray = array.flatMap { $0 }
    

    flatArray now is [person1, person2, person3, person9, person10, person11] of type Array.

    Then you can iterate on flatArray to find what you want :

    for person in flatArray {
        if person.name == "Masha" {
            // Do something
        }
    }
    

    You could even go further by using Swift 2.0 because it allows you to put a where clause in the for :

    for person in flatArray where person.name == "Masha" {
        // Do something
    }
    

提交回复
热议问题