Accessing variables from one function to another Swift

1.3k Views Asked by At

So this seems like a simple question and probably has a very simple solution but haven't been able to work this out. I have a variable formed in a function and I want to use 'newPlace', 'place' and 'place.name' in another function... how do I make it a non-local variable? I would like to put the storedPlaces.append(newPlace) into another function but it tells me newPlace is an undefined variable...and obviously when I put the let newPlace=.... underneath the class it doesn't cannot identify 'place'. I tried to put var place: GMSPlace? at the top but that also doesn't work.

Here is the relevant code:

     func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {

        let camera = GMSCameraPosition.camera(withLatitude: place.coordinate.latitude, longitude: place.coordinate.longitude, zoom: 15.0)
        self.vwGMap.camera = camera
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2DMake(place.coordinate.latitude, place.coordinate.longitude)
   marker.title = place.name
    marker.snippet = place.formattedAddress
        marker.map = self.vwGMap
        marker.icon = GMSMarker.markerImage(with: UIColor.blue)
        marker.tracksViewChanges = true
        self.dismiss(animated: true, completion: nil)
        print("Place name: ", place.name)
        print("Place address: ", place.formattedAddress)
        print("Place placeID: ", place.placeID)
        print("Place attributions: ", place.attributions)
        print("Place Coordinate:", place.coordinate)
        //The printing only happens in the terminal
        let newPlace = StoredPlace(name: place.name, address: place.formattedAddress!, placeID: place.placeID)
        storedPlaces.append(newPlace)

           }

and this is at the top of the class:

    var storedPlaces: [StoredPlace] = []
1

There are 1 best solutions below

0
On BEST ANSWER

Also at the top of the class add

var place:GMSPlace?
var newPlace:StoredPlace?

and in your function just assign them

func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
    self.place = place
    ....
    self.newPlace = StoredPlace(name: place.name, address: place.formattedAddress!, placeID: place.placeID)
}