Wrapping models in SwiftUI for Identifiable conformance
Using array of models in List view in SwiftUI requires conformance to Identifiable protocol.
Here's an example of model:
struct MyDataModel {
let title: String
let message: String
}
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 you error in Xcode:
Sometimes you can't just change the model. It might be a data model from third part SDK that you're using in you 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 List")
let wrappedData = MyDataModelWrapper(data: testDataModel)
So view will look like this:
struct TestView: View {
var dataArray: [MyDataModelWrapper]
var body: some View {
List(dataArray) { wrappedData in
VStack {
Text(wrappedData.data.title)
Text(wrappedData.data.message)
}
}
}
}
Done.
keyboard_return back