Hi, so I have been learning SwiftUI and writing an app. I have found out that the following code won't compile and neither Xcode shows the preview of that view. Instead Xcode will display this error message when I try to preview it:
Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project
Just to demonstrate this issue, all MVVM code are in a single file. Here's my code:
// Model
struct WatchListModel {
let m_id: Int
let m_ticker_symbol: String
}
// View
struct WatchlistView: View {
@ObservedObject var m_watch_list_view_model: WatchListViewModel
init(watch_list_view_model: WatchListViewModel) {
m_watch_list_view_model = watch_list_view_model
}
var body: some View {
// This view is causing that issue
List(m_watch_list_view_model.m_watch_list_model) { watch_list_model in
Text(watch_list_model.m_ticker_symbol)
}.onAppear(perform: {
self.m_watch_list_view_model.populate_watch_list()
})
}
}
extension WatchlistView {
// View model
class WatchListViewModel: ObservableObject {
@Published var m_watch_list_model: [WatchListModel] = []
// Populate watch list
func populate_watch_list() {
for index in 0...10 {
m_watch_list_model[index] = WatchListModel(m_id: index, m_ticker_symbol: "Foo")
}
}
}
}
struct WatchlistView_Previews: PreviewProvider {
static private var m_watch_list_view_model: WatchlistView.WatchListViewModel = .init()
static var previews: some View {
WatchlistView(watch_list_view_model: self.m_watch_list_view_model)
}
}
I am using Xcode 12.5, though it's not the latest version. The above bug can eradicated if I remove List view and just output the contents of that array as Text view. Is there anything I can do to get around this bug?
There may be an identifier missing .
Replace
List(m_watch_list_view_model.m_watch_list_model) { watch_list_model in
with
List(m_watch_list_view_model.m_watch_list_model, id: \.id) { watch_list_model in
Note: the use of underscore in name is not Switish at all. Remove them and replace by camelCase.
For instance
m_watch_list_view_model
should become
mWatchListViewModel
furthermore, the starting m has not clear meaning.
So you could replace with
watchListViewModel