2016-12-23 14 views
0

これは簡単な質問のようであり、おそらく非常に簡単な解決策を持っていますが、これを実行できませんでした。私は関数内に変数が形成されているので、別の関数で 'newPlace'、 'place'、 'place.name'を使いたいのです...どうすれば非ローカル変数にするのですか?私はstoredPlaces.append(newPlace)を別の関数に入れたいと思っていますが、newPlaceは未定義の変数であると私に伝えています。そしてlet newPlace = ....を明示的に置くと、クラスの下には '場所'。私はvar場所を入れようとしました:GMSPlace?しかし、それもうまくいきません。ある関数から別の関数への変数へのアクセスSwift

 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] = [] 
+0

あなたのクラスは複数回に分けられますか?もしそうでなければ、シングルトンを使うことができます。 – Makaille

+0

あなたのクラスのどの場所にでもstoredPlacesを初期化しましたか:var storedPlaces:[StoredPlace] = []もしそうなら、あなたがしていることはうまくいくはずです。コード内のどこでも配列を無効にしていないことを確認してください。 – jvarela

答えて

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) 
} 
+0

これは完璧です!!!!!!ありがとうございました! –

関連する問題