I try to create a List from an array containing types which are conforming to a protocol.
I can map and downcast the types in .onAppear, but I can’t use the array as a source for the List and do the downcast to create text views.
Compiler message is
‘Type ‘any IRow’ cannot conform to ‘Identifiable’’
If I use id like this
List(item.rows, id: .self)
the compiler message is about
‘cannot conform to ‘Hashable’
protocol IRow: Identifiable, Hashable {
var id: UUID { get }
var rowType: String { get }
}
struct TextItemRow: IRow {
let id = UUID()
let rowType = "text"
var text: String = ""
}
struct HeadlineItemRow: IRow {
let id = UUID()
let rowType = "headline"
var text: String = ""
}
struct Item: Identifiable {
let id = UUID()
var rows: [any IRow] = [HeadlineItemRow(text: "H_mock"), TextItemRow(text: "T_mock")]
}
struct ContentView: View {
let item = Item()
var body: some View {
VStack {
List(item.rows) { row in
}
}
.onAppear {
var _ = item.rows.map() {
if let r = $0 as? HeadlineItemRow {
print("(r.id.uuidString) : (r.text)")
} else if let r = $0 as? TextItemRow {
print("(r.id.uuidString) : (r.text)")
}
}
}
}
}
0
Try List(item.rows, id: .id) { row in ...}
, works for me.