Using an array of models in List view in SwiftUI requires conformance to Identifiable protocol.
Here's an example of a model:
struct MyDataModel {
let title: String
let message: String
}
An example of SwiftUI view that you want to display a list:
struct TestView: View {
var dataArray: [MyDataModel]
var body: some View {
List(dataArray) { data in
VStack {
Text(data.title)
Text(data.message)
}
}
}
}
Using MyDataModel in List will show an error in Xcode:
Sometimes you can't just change a model. It might be a data model from a third party SDK that you're using in your app. But you can create a wrapper for this struct to confirm Identifiable protocol:
struct MyDataModelWrapper: Identifiable {
var id = UUID()
var data: MyDataModel
}
let testDataModel = MyDataModel(
title: "Title 1",
message: "I wanna be used inside of a List"
)
let wrappedData = MyDataModelWrapper(data: testDataModel)
So the view will look like this:
struct TestView: View {
var dataArray: [MyDataModelWrapper]
some View {
List(dataArray) { wrappedData in
VStack {
Text(wrappedData.data.title)
Text(wrappedData.data.message)
}
}
}
}
Done.