Whenever I changed the @State variables to @Published and moved them out of ContentView into a new ContentView-ViewModel file, I get the error I mentioned in the title for this post.
Before I moved the properties out of ContentView, and they were @State properties, my code all compiled without any issues. However, when I moved these into a new file called "ContentView-ViewModel.swift" and made them @Published variables, and also initialized a new variable viewModel = ViewModel() and added viewModel. in the appropriate locations, I receive this error in my ContentView struct. Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs)
I wasn't able to solve the issue with ChatGPT, looking through the forums or Stackoverflow, so any help would be greatly appreciated.
Here is my code:
//
// ContentView.swift
// BucketList
//
// Created by user239371 on 6/6/23.
//
import SwiftUI
import MapKit
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
ZStack {
Map(coordinateRegion: viewModel.$mapRegion, annotationItems: viewModel.locations) { location in
MapAnnotation(coordinate: location.coordinate) {
VStack {
Image(systemName: "star.circle")
.resizable()
.foregroundColor(.red)
.frame(width: 44, height: 44)
.background(.white)
.clipShape(Circle())
Text(location.name)
.fixedSize()
}
.onTapGesture {
viewModel.selectedPlace = location
}
}
}
.ignoresSafeArea()
Circle()
.fill(.blue)
.opacity(0.3)
.frame(width:32, height: 32)
VStack {
Spacer()
HStack {
Spacer()
Button {
let newLocation = Location(id: UUID(), name: "New Location", description: "", latitude: viewModel.mapRegion.center.latitude, longitude: viewModel.mapRegion.center.longitude)
viewModel.locations.append(newLocation)
} label: {
Image(systemName: "plus")
}
.padding(20)
.background(.black.opacity(0.75))
.foregroundColor(.white)
.clipShape(Circle())
.padding(.trailing)
}
}
}
.sheet(item: viewModel.$selectedPlace) { place in
Text(place.name)
EditView(location: place) { newLocation in
if let index = viewModel.locations.firstIndex(of: place) {
viewModel.locations[index] = newLocation
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
import Foundation
import MapKit
extension ContentView {
@MainActor class ViewModel: ObservableObject {
@Published var mapRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 50, longitude: 0), span: MKCoordinateSpan(latitudeDelta: 25, longitudeDelta: 25))
@Published var locations = [Location]()
@Published var selectedPlace: Location?
}
}