UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.