I've written a simple list in SwiftUI that accepts a generic data type.
The goal was to make a reusable list where when an item was selected, the list would execute a callback with the selected data.
I struggled with it for a while and have my doubts so I'm keen to get feedback on my implementation.
struct ContentView: View { var body: some View { VStack { BottomSheetView<Test>(options: [Test(name: "hi", type: 7)], selectedOptionsCompletion: {value in}) BottomSheetView<Test2>(options: [Test2(name: "hi again", type: "7")], selectedOptionsCompletion: {value in}) } .padding() } } struct BottomSheetView<T: ListItem>: View { var options: [T] var selectedOptionsCompletion: ((T.DataType) -> Void)? var body: some View { VStack(alignment: .leading, spacing: 5) { ForEach(options) {item in Text(item.name).onTapGesture { let _ = print(type(of: item.type)) selectedOptionsCompletion!(item.type) } } } .presentationDetents([.medium, .fraction(0.15)]) .presentationDragIndicator(.hidden) .padding() } } protocol ListItem: Identifiable { var id: UUID {get} var name: String { get set} associatedtype DataType var type: DataType { get set} } struct Test: ListItem { var id: UUID = UUID() var name: String var type: Int init(name: String, type: Int) { self.name = name self.type = type } } struct Test2: ListItem { var id: UUID = UUID() var name: String var type: String init(name: String, type: String) { self.name = name self.type = type } }