How To Iterate Array Of Objects To Create Views In SwiftUI

In SwiftUI we can’t easily iterate via an array of objects inside the view as it was in UIKit, however, it’s still possible and it’s really simple.

Let’s assume you have a simple struct and array of its instances.

struct User {
    let name: String
    let age: Int
}

private let users = [User(name: “John”, age: 32), User(name: “Stephanie”, age: 32)]

Here, I assume you don’t want to use Hashable because conforming to Hashable also solves the issue.

If you try to use ForEach like that:

var body: some View {
    ForEach(users, id: \.self) { user in
        Text(“User: \(user.name), age: \(user.age))
    }
}

You’ll receive error:

Generic struct ‘ForEach’ requires that ‘User’ conform to ‘Hashable’

Instead of conforming to Hashable you can do something different.

Create an array of enumerated elements, change self to offset and inside loop, add element part.

ForEach(Array(users.enumerated()), id: \.offset) { user in
    Text(“User: \(user.element.name), age: \(user.element.age))
}

Thanks to that you don’t need to conform to Hashable and you can iterate an array of objects inside the view.