0

I tried to list a array of struct with swiftUI.

import SwiftUI

struct User: Codable {
    var id: UUID
    var name: String
}

struct MyView: View {
    @State private var users = [User]()

    var body: some View {
        List(users, id: \.id) {    // Type '_' has no member 'id'
            VStack(alignment: .leading) {
                Text($0.name)
                    .font(.headline)
            }
        }
    }
    ...
}

But the compiler report a error show that User struct has no id property.

1
  • I think it should be var id: UUID() and the User struct ought to conform to Identifiable as well Commented Mar 11, 2020 at 15:08

2 Answers 2

2

It should be like below

var body: some View {
    List(users, id: \.id) { user in   // << here !!
        VStack(alignment: .leading) {
            Text(user.name)           // << due to in different block
                .font(.headline)
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

At first adding id property is not enough, User has to conform to Identifiable

struct User: Identifiable, Codable {
    var id: UUID
    var name: String
}

Next is easy to use it as the source of List

struct ContentView: View {
    @State private var users = [User]()

    var body: some View {
        VStack {
            List(users) {
                Text($0.name)
                    .font(.headline)
            }
            Button(action: {
                let u = User(id: UUID(), name: "Name \(Int.random(in: 0 ..< Int.max))")
                self.users.append(u)
            }) {
                Text("Add User")
            }
        }
    }
}

List knows the id property exists, so you don't need to use it in the List constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.