How to iterate through array of objects in Swift?

后端 未结 6 808
慢半拍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 02:58

    Here is technique which called 'Chaining'

    Playground. Swift 3.1

    import UIKit
    
    class Person {
        var name = ""
        var lastName = ""
        var age = 0
    }
    
    var person1 = Person()
    person1.name = "Joe"
    person1.lastName = "Doe"
    person1.age = 21
    
    var person2 = Person()
    person2.name = "Julia"
    person2.lastName = "Ivanova"
    person2.age = 22
    
    var person3 = Person()
    person3.name = "Irina"
    person3.lastName = "Petrova"
    person3.age = 25
    
    var person9 = Person()
    person9.name = "Vova"
    person9.lastName = "Vovin"
    person9.age = 32
    
    var person10 = Person()
    person10.name = "Masha"
    person10.lastName = "Golovanova"
    person10.age = 20
    
    var person11 = Person()
    person11.name = "Petra"
    person11.lastName = "Andreeva"
    person11.age = 27
    
    var array = [[person1, person2, person3], [person9, person10, person11]]
    
    array
        .flatMap{$0}
        .forEach { (anyPerson:Person) in
    
            if anyPerson.name == "Masha" {
                //Do what you need
                print(anyPerson.lastName)
            }
    }
    

    Screen-shot from playground:

提交回复
热议问题