Home > Software design >  How to use array of ForEach in SwiftUI
How to use array of ForEach in SwiftUI

Time:04-22

I would like to create an array with a ForEach loop.

Something like this :

let a = [
    ForEach(b) { c in
         "create the element in the array"
    }
]

Here is the code I tried :

let places = [
    ForEach(viewModel.posts) { post in
        Place(latitude: post.location.latitude, longitude: post.location.longitude)
    }
]

But I have an error :

Static method 'buildBlock' requires that 'Place' conform to 'AccessibilityRotorContent'

Do you have any idea ?

CodePudding user response:

As @jnpdx said, you can use the map(...) method of Array to accomplish your goal:

let places: [Place] = viewModel.posts.map { post in
  Place(latitude: post.location.latitude, longitude: post.location.longitude)
}
  • Related