Cannot find withAnimation in scope error

I have the following code and when trying to add Animation, I get the following error: "Cannot find 'withAnimation' in scope error" Is there something I'm missing please? import Foundation import MapKit class LocationsViewModel: ObservableObject {

//All loaded locations @Published var locations: [Locations]

//Current location on the map @Published var mapLocation: Locations

@Published var mapRegion: MKCoordinateRegion = MKCoordinateRegion() let mapSpan = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)

init() { let locations = LocationsDataService.locations self.locations = locations self.mapLocation = locations.first!

self.updateMapRegion(locations: locations.first!)

}

private func updateMapRegion (locations:Locations) { withAnimation(.easeInOut) { mapRegion = MKCoordinateRegion( center: Locations.coordinates, span: mapSpan) }

You are new to the forum, welcome.

When you post code, please use code formatting tool. As is, your code is unreadable.

import Foundation
import MapKit

class LocationsViewModel: ObservableObject {
     //All loaded locations
     @Published var locations: [Locations]
     //Current location on the map
     @Published var mapLocation: Locations
     @Published var mapRegion: MKCoordinateRegion = MKCoordinateRegion()
     let mapSpan = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
     init() {
          let locations = LocationsDataService.locations
          self.locations = locations
          self.mapLocation = locations.first!
          self.updateMapRegion(locations: locations.first!)
     }
     private func updateMapRegion (locations:Locations) { withAnimation(.easeInOut) {
          mapRegion = MKCoordinateRegion( center: Locations.coordinates, span: mapSpan)
     }
     }
}

There are several errors or omissions:

  • Where is Locations defined (it should probably be named Location)
  • what is this syntax ?
  • what do you try to animate ?
func updateMapRegion (locations:Locations) { withAnimation(.easeInOut) {

When you call

mapRegion = MKCoordinateRegion( center: Locations.coordinates, span: mapSpan)

you probably mean

mapRegion = MKCoordinateRegion( center: locations.coordinates, span: mapSpan) // locations not Locations

But locations is an array, so locations.coordinates is incorrect. It should probably be locations[someIndex].coordinates

You should study a bit more the basics of Swift and app development before trying to write such code.

You should need to import SwiftUI in your file. I think that's the issue.

Import SwiftUI

Cannot find withAnimation in scope error
 
 
Q