How to use protocol in List in SwiftUI
Issue #446
Suppose we have Service protocol, and want to use in List
1 | protocol Service { |
1 | struct MainView: View { |
This is not possible because item in List needs to conform to Identifiable
Protocol type ‘Service’ cannot conform to ‘Identifiable’ because only concrete types can conform to protocols
Type eraser
In the same way that SwiftUI uses type eraser, for example AnyView
, we can introduce AnyService
to work around this
1 | var body: some View { |
Make AnyService conform to Identifiable
1 | struct AnyService: Identifiable { |
Then in our View, we just need to declare services wrapped inside AnyService
1 | struct MainView: View { |
A bit refactoring, we can just declare normal services and map them
1 | struct MainView: View { |