How to iterate through array of objects in Swift?

后端 未结 6 810
慢半拍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:25

    Iterating can be done as in @Rachel's answer. However there are different ways of doing the same thing, and not necessarily by iterating - and in some cases with just one line of code.

    If you want to find, then the best way is using the array's filter method - but before that the multi dimensional array should be flattened, using flatMap.

    So, to find the first element having a certain name, you can simply do:

    let result: Person? = array.flatMap { $0 }.filter { $0.name == "Masha" }.first
    

提交回复
热议问题