How to iterate through array of objects in Swift?

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

    Here is a pretty simple way to do what you need:

    let result = array
        .flatMap { $0 }
        .first(where: { $0.name == "Masha" })
    

    First you have to make your array flatted and then you can just get the first element from the array that satisfies the given predicate (in our case, where name is equal to "Masha").

提交回复
热议问题