从一个函数访问变量到另一个函数Swift

时间:2016-12-23 16:19:56

标签: ios swift google-maps variables local-variables

所以这看起来像一个简单的问题,可能有一个非常简单的解决方案,但无法解决这个问题。我在函数中形成了一个变量,我想在另一个函数中使用'newPlace','place'和'place.name'...如何使它成为非局部变量?我想把storedPlaces.append(newPlace)放到另一个函数中但它告诉我newPlace是一个未定义的变量......显然当我把let newPlace = ....放在类下面时它不能识别'地点'。我试着把var放在地方:GMSPlace?在顶部,但也不起作用。

以下是相关代码:

     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)

           }

这是课程的最高层:

    var storedPlaces: [StoredPlace] = []

1 个答案:

答案 0 :(得分:0)

同样在课程顶部添加

var place:GMSPlace?
var newPlace:StoredPlace?

并在您的函数中指定它们

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