TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED - Confusion with Project 14 - Introduction to MVVM

Forums > 100 Days of SwiftUI

That will of course break a lot of code, but the fixes are easy – just add viewModel in various places. So, locations becomes $viewModel.locations, and selectedPlace becomes viewModel.selectedPlace.

Except it's not easy. I added "viewModel" to all the instances of "locations" and "selectedPlace" but I'm getting errors on the Annotation block. Here's the relevant part of my code:

        MapReader { proxy in
            Map(initialPosition: startPosition) {
                ForEach($viewModel.locations) { location in
                    Annotation(location.name, coordinate: location.coordinate) {
                        Image(systemName: "star.circle")
                            .resizable()
                            .foregroundStyle(.red)
                            .frame(width: 44, height: 44)
                            .background(.white)
                            .clipShape(.circle)
                            .onLongPressGesture {
                                viewModel.selectedPlace = location
                            }
                    }
                }
            }
            .onTapGesture { position in
                if let coordinate = proxy.convert(position, from: .local) {
                    let newLocation = Location(id: UUID(), name: "New location", description: "", latitude: coordinate.latitude, longitude: coordinate.longitude)
                    viewModel.locations.append(newLocation)
                }
            }
            .sheet(item: $viewModel.selectedPlace) { place in
                EditView(location: place) { newLocation in
                    if let index = viewModel.locations.firstIndex(of: place) {
                        viewModel.locations[index] = newLocation
                    }
                }
            }
        }

The errors are:

Cannot assign to property: 'coordinate' is a get-only property

Cannot assign value of type 'Binding<[Location]>.Element' (aka 'Binding<Location>') to type 'Location'

1      

Remove $ aka binding in this line

ForEach(viewModel.locations)

1      

Well that's very strange. The article seems to be wrong. Thank you.

1      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.